【问题标题】:How to enable/disable button for a given interval如何在给定的时间间隔内启用/禁用按钮
【发布时间】:2021-05-05 05:27:06
【问题描述】:
class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My Window")
        self.setGeometry(400, 400, 400, 200)
        
        btn1 = QPushButton("button1", self)
        btn1.move(20, 20)
        btn1.clicked.connect(self.btn1_clicked)

        btn2 = QPushButton("button2", self)
        btn2.move(20, 70)
        btn2.clicked.connect(self.btn2_clicked)


    def btn1_clicked(self):
        btn1function

    def btn2_clicked(self):
        btn2function

假设我想在上午 9 点激活 btn1 功能,在上午 10 点激活 btn2 功能,并在功能激活 5 分钟后自动停用该功能。我尝试放置在上午 9 点和 5 分钟后断开的循环,但发生了错误。

我该怎么做?

【问题讨论】:

  • 像 Qt 这样的 UI 框架是 event driven,它们对来自系统或用户交互的事件做出反应,因此它们永远不会被 time.sleep 等函数阻止或 while 循环。虽然可以使用QTimer 激活您的函数,但它们所做的不应使用任何类型的阻塞,因此应将它们放在单独的线程中。对此进行一些研究,并考虑 no 允许从其他线程访问 ui 元素,因此查找 QThread 和自定义信号。

标签: python pyqt qpushbutton


【解决方案1】:

这可以通过使用single-shot timers 启用/禁用按钮和QTime 来计算间隔来完成。下面的演示脚本展示了如何实现它:

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

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle("My Window")
        self.setGeometry(400, 400, 400, 200)

        self.btn1 = QPushButton("button1", self)
        self.btn1.move(20, 20)
        self.btn1.clicked.connect(self.btn1_clicked)

        self.btn2 = QPushButton("button2", self)
        self.btn2.move(20, 70)
        self.btn2.clicked.connect(self.btn2_clicked)
        
        # begin after 3 secs, end 5 secs later
        begin = QTime.currentTime().addSecs(3)
        self.configureButton(self.btn1, begin, 5)

        # begin after 10 secs, end 3 secs later
        begin = QTime.currentTime().addSecs(10)
        self.configureButton(self.btn2, begin, 3)

        # begin 9:00am, stop after 5 mins
        # self.configureButton(self.btn1, QTime(9, 0), 5 * 60)

        # begin 10:00am, stop after 5 mins
        # self.configureButton(self.btn2, QTime(10, 0), 5 * 60)

    def configureButton(self, button, begin, duration):
        end = begin.addSecs(duration)
        now = QTime.currentTime()
        button.setEnabled(begin <= now <= end)
        if now < begin:
            QTimer.singleShot(
                now.msecsTo(begin), lambda: button.setEnabled(True))
        if now < end:
            QTimer.singleShot(
                now.msecsTo(end), lambda: button.setEnabled(False))

    def btn1_clicked(self):
        print('btn1 clicked')

    def btn2_clicked(self):
        print('btn2 clicked')


if __name__ == '__main__':

    app = QApplication(sys.argv)
    window = MyWindow()
    window.show()
    sys.exit(app.exec_())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-24
    相关资源
    最近更新 更多