正确使用QTimer.singleShot

2024-04-30 04:23:07 发布

您现在位置:Python中文网/ 问答频道 /正文

我有以下PySide应用程序,其中的预期功能是让number_button的文本每5秒更新一次,按下start_button后从0到9计数。


import sys
from PySide import QtGui, QtCore

class Example(QtGui.QWidget):

    def __init__(self, parent=None):
        super(Example, self).__init__(parent)

        self.app_layout = QtGui.QVBoxLayout()
        self.setLayout(self.app_layout)

        self.setGeometry(300, 300, 50, 50)

        self.count_to = 10
        self.delay = 5000

        self.timer = QtCore.QTimer(self)
        self.timer.setSingleShot(True)

        # start button
        start_button = QtGui.QPushButton()
        start_button.setText('START')
        start_button.clicked.connect(self.startCount)
        self.app_layout.addWidget(start_button)

        # number button
        self.number_button = QtGui.QPushButton()
        self.number_button.setText('0')
        self.app_layout.addWidget(self.number_button)



    def startCount(self):

        def updateButtonCount():
            self.number_button.setText("%s" % count)

        for count in range(0, self.count_to):
            self.timer.singleShot(self.delay, updateButtonCount)


def main():

    app = QtGui.QApplication(sys.argv)
    example = Example()
    example.show()
    sys.exit(app.exec_())


if __name__ == '__main__':
    main()

但是,这会导致在6秒后出现一个9,根本不显示中间数字。我确信问题在于当.singleShot运行时,count已经增加到其最大值(9)。

我可以想出一些方法来让它按预期工作,但我想用最有效和最适当的方式来修复它。


Tags: selfappnumbermainexampledefcountsys
1条回答
网友
1楼 · 发布于 2024-04-30 04:23:07

正如QTimerPySide文档中所提到的,您需要的是一个QTimer,它将重复超时(在您的情况下,每5秒一次),并为每个超时调用一次函数updateButtonCount,如aruistante所述。看看这个:

timer = QTimer()  # set up your QTimer
timer.timeout.connect(self.updateButtonCount)  # connect it to your update function
timer.start(5000)  # set it to timeout in 5000 ms

经过一些修改,前面的代码应该可以帮助您实现所需的功能。请记住,timer.start(5000)只设置一个超时,在5000毫秒内发生,或者设置为5秒,如果QTimer要再次超时,那么updateButtonCount函数应该在末尾包含这一行。

我希望这会有帮助。如果有不清楚的地方,请随意评论。

相关问题 更多 >