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

时间:2019-04-15 11:23:08

标签: python pyqt

我想在单击并按住按钮一定时间后发送“连接”信号。经过这段时间(例如10秒)后,即使未释放按钮,动作或事件也会被触发。可以是单击或按住一会儿的组合,也可以是其他任何操作,然后只需单击并释放按钮即可。

3 个答案:

答案 0 :(得分: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

答案 1 :(得分: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();
}

换句话说,这是C ++中非常基本的Qt应用程序,如果您正在使用Qt Creator,则在创建第一个Qt项目时会为您填充。希望这段代码阐明了如何实现所需的想法。如果您还有其他问题,请提出。希望我能为您提供帮助。

答案 2 :(得分: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_())   

在窗口上按住鼠标的算法

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

鼠标按住按钮的算法

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