hog90160720
hog90160720

Reputation: 45

How to enable/disable button for a given interval

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

Let's say I want to activate btn1function at 9AM, and btn2function at 10Am and automatically deactivate the function 5 minutes after the function has been activated. I tried putting loops that get broken at 9AM and after 5 minutes, but an error occured.

How can I do this?

Upvotes: 2

Views: 535

Answers (1)

ekhumoro
ekhumoro

Reputation: 120798

This can be done by using single-shot timers to enable/disable the buttons, and QTime to calculate the intervals. The followimg demo script shows how to implement that:

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_())

Upvotes: 3

Related Questions