繁体   English   中英

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

[英]is there any time limit in pushing the push button in pyqt5?

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

您必须使用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_())

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM