如何在给定的时间间隔内启用/禁用按钮

问题描述

class MyWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setwindowTitle("My Window")
        self.setGeometry(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 点激活 btn1function,在上午 10 点激活 btn2function,并在该功能激活 5 分钟后自动停用该功能。我尝试放置在上午 9 点和 5 分钟后中断的循环,但发生错误

我该怎么做?

解决方法

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

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,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,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,5 * 60)

    def configureButton(self,button,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_())