按住鼠标按钮10秒PyQt Python后连接信号

问题描述 投票:1回答:3

我想在点击并按住按钮一段时间后发送“连接”信号。在该时间过后(f.e 10秒),即使没有释放按钮,也会触发动作或事件。它可以是点击或保持一段时间或任何不同的组合,然后只需单击并释放按钮。

python pyqt
3个回答
0
投票

这是我在PyQt4上测试的代码

import sys
from PyQt4.QtCore import *
from PyQt4.QtGui import * 

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()

        #Creation of a sample Window
        self.textLabel = QLabel()
        self.textLabel.setText('This is a Sample Window')
        box = QHBoxLayout(self)
        box.addWidget(self.textLabel)

        #Create a Timer
        self.timer = QTimer()
        self.timer.timeout.connect(lambda: self.mouse_event_check())
        self.held_time = 0

        #Create Sample Button
        self.button = QPushButton('SAMPLE BUTTON')
        box.addWidget(self.button)

        #Connect Signals Pressed and Released
        self.button.pressed.connect(self.button_pressed)
        self.button.released.connect(self.button_released)

        self.timer_button = QTimer()
        self.timer_button.timeout.connect(lambda: self.button_event_check())
        self.button_held_time = 0

    # =========================================================================
    # Implementation for Buttons
    # =========================================================================
    def button_pressed(self):
        self.timer_button.start(50)

    def button_released(self):
        self.timer_button.stop()
        print('Button Held for {:.4f} seconds'.format(self.button_held_time))
        self.button.setText('{:.4f} seconds'.format(self.button_held_time))
        self.button_held_time = 0 

    def button_event_check(self):
        self.button_held_time += 0.05

    # =========================================================================
    # Implmentation for Mouse Held on Window
    # =========================================================================
    def mousePressEvent(self, mouse_event):
        self.timer.start(50)

    def mouse_event_check(self):
        self.held_time += 0.05

    def mouseReleaseEvent(self, mouse_event):   
        self.timer.stop()
        print('Mouse Held for {:.4f} seconds'.format(self.held_time))
        self.textLabel.setText('Mouse Held for {:.4f} seconds'.format(self.held_time))

        self.held_time = 0


if __name__ == '__main__':  
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())   

Algorithm for Mouse Hold on Window

  1. 创建一个held_time变量。将其设置为0
  2. 创建一个计时器
  3. 将timer的timeout()信号连接到一个函数(mouse_event_check
  4. 重新实施MousePressEvent() 启动定时器(50毫秒)
  5. 重新实施MouseReleaseEvent() 停止计时器 将held_time重置为0
  6. 实施mouse_event_check() 将hold_time变量增加0.05

Algorithm for Mouse Hold on Button

  1. 创建一个button_held_time变量。将其设置为0
  2. 创建一个计时器
  3. 将timer的timeout()信号连接到一个函数(button_event_check
  4. 将按钮信号pressedreleased连接到一些callables
  5. 实施pressed方法 启动计时器(50毫秒)
  6. 实施released方法 停止计时器 将button_held_time重置为0
  7. 实施button_event_check() 将hold_time变量增加0.05

0
投票

试试吧:

import sys
from PyQt5.QtCore    import *
from PyQt5.QtWidgets import * 

class MainWindow(QWidget):
    def __init__(self):
        super().__init__()
        self.textLabel = QLabel()
        button = QPushButton("Click me")
        button.clicked.connect(self.clickedButton)
        grid = QGridLayout(self)
        grid.addWidget(self.textLabel)
        grid.addWidget(button)

    def clickedButton(self):
        QTimer.singleShot(3000, self.passed3seconds)                # <---

    def passed3seconds(self):
        self.textLabel.setText("3 seconds passed \n do something")

if __name__ == '__main__':  
    app = QApplication(sys.argv)
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())        

enter image description here


0
投票

我认为你可以依赖QTimer的使用,即当用户点击按钮时,你可以用指定的间隔启动一些​​QTimer实例,当QTimer超时时,然后触发一个信号。如果用户中止操作,可以重置QTimer,然后不会触发信号。示例代码如下所示。但是,它是在C ++中,但也许对你来说不是问题。

所以,下面是MainWindow的定义:

#pragma once
#include <memory>

#include <QMainWindow>

namespace Ui
{
    class MainWindow;
}

class MainWindow
    : public QMainWindow
{
    Q_OBJECT
public:
    MainWindow(QWidget *parent = nullptr);
    virtual ~MainWindow();

signals:
    void SomeTimerSignal(); // Signal we are eager to fire on the specific event.

public slots:
    void ButtonPressed(); // Button is clicked down.
    void ButtonReleased(); // Button is released.
    void OnTimeout(); // Timeout handling slot.

private:
    std::unique_ptr<Ui::MainWindow> m_ui; // UI mockup that is provided by Qt for us under the hood.
    QTimer* m_buttonTimer; // The timer we are going to control.
};

现在代码本身实现了这个定义:

#include <QPushButton>
#include <QTimer>
#include <QVBoxLayout>

#include "MainWindow.h"
#include "ui_MainWindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , m_ui(new Ui::MainWindow())
{
    m_ui->setupUi(this);

    // We could have chosen to instantiate timers on each signal, but it is much more efficient
    //   to create an instance of it once, and then use it appropriately.
    m_buttonTimer = new QTimer(this);

    // OnTimeout will get triggered after 10 seconds.
    m_buttonTimer->setInterval(10000);
    connect(m_buttonTimer, &QTimer::timeout, this, &MainWindow::OnTimeout);

    auto layout = new QVBoxLayout();
    auto button = new QPushButton();
    button->setText("Click and hold me!");
    button->setFixedSize(150, 50);
    layout->addWidget(button);

    m_ui->centralWidget->setLayout(layout);

    // Listen to button being pressed down: https://doc.qt.io/qt-5/qabstractbutton.html#pressed
    connect(button, &QPushButton::pressed, this, &MainWindow::ButtonPressed);

    // Listen to button being released: https://doc.qt.io/qt-5/qabstractbutton.html#released
    connect(button, &QPushButton::released, this, &MainWindow::ButtonReleased);
}

MainWindow::~MainWindow()
{
    // Button timer will be taken care by Qt through its' memory model.
}

void MainWindow::ButtonPressed()
{
    // Start the timer when button is pressed.
    m_buttonTimer->start();
}

void MainWindow::ButtonReleased()
{
    // Stop the timer, but don't delete it, since it can be reused.
    m_buttonTimer->stop();
}

void MainWindow::OnTimeout()
{
    // On timeout, we stop the timer, so it would not be triggered all over again when not needed.
    m_buttonTimer->stop();

    // And we fire some wanted signal.
    emit SomeTimerSignal();
}

为了使用此代码,您可能希望以下列方式实例化应用程序:

#include "MainWindow.h"
#include <QApplication>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    MainWindow w;
    w.show();

    return a.exec();
}

换句话说,如果您正在使用Qt Creator,那么在创建您的第一个Qt项目时,它是C ++中非常基本的Qt应用程序。希望这段代码能够澄清您如何实现自己想要的目标。如果您还有其他问题,请询问。希望我能帮到你。

© www.soinside.com 2019 - 2024. All rights reserved.