按下pyqt5中的按钮有时间限制吗?

时间:2019-02-28 04:45:32

标签: python pyqt pyqt5

我正在做一个通过回答问题来扩散炸弹的游戏。有什么方法可以等待用户在特定时间按下按钮?并且当该特定时间用完时,该按钮将被禁用。谢谢您的回答:)

1 个答案:

答案 0 :(得分:2)

您必须使用QTimer来实现逻辑:

from PyQt5 import QtCore, QtWidgets
from functools import partial

class Widget(QtWidgets.QWidget):
    def __init__(self, parent=None):
        super(Widget, self).__init__(parent)
        button = QtWidgets.QPushButton(
            text='Start Game',
            clicked=self.on_start_game_clicked
        )
        self.game_button = QtWidgets.QPushButton(
            text='Press me',
            clicked=self.on_game_clicked
        )
        self.time_label = QtWidgets.QLabel(alignment=QtCore.Qt.AlignCenter)

        lay = QtWidgets.QVBoxLayout(self)
        lay.addWidget(button)
        lay.addWidget(self.game_button)
        lay.addWidget(self.time_label)

        self.timer = QtCore.QTimer(self, 
            interval=5000, # time in ms
            timeout=partial(self.game_button.setDisabled, True),
            singleShot=True
        )
        self.time_timer = QtCore.QTimer(self,
            interval=100,
            timeout=self.update_label
        )

    @QtCore.pyqtSlot()
    def on_start_game_clicked(self):
        if not self.timer.isActive():
            self.timer.start()
            self.time_timer.start()
            self.game_button.setEnabled(True)

    @QtCore.pyqtSlot()
    def update_label(self):
        if self.timer.remainingTime() >= 0:
            self.time_label.setText('{0:.2f} ms'.format(self.timer.remainingTime()*0.001))
        else:
            self.time_label.setText('0 ms')

    @QtCore.pyqtSlot()
    def on_game_clicked(self):
        print("clicked")


if __name__ == '__main__':
    import sys
    app = QtWidgets.QApplication(sys.argv)
    w = Widget()
    w.show()
    sys.exit(app.exec_())