我有以下PySide应用程序,其中预期的功能是每隔5秒更新number_button
的文本,一旦按下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
)。
我可以想到一些hack来使这项工作按预期进行,但我想以最有效和最恰当的方式解决它。
答案 0 :(得分:1)
正如QTimer PySide文档中所提到的,你需要的是一个QTimer会反复超时(在你的情况下每5秒)并且每次超时都会调用函数updateButtonCount
- 如上所述通过 aruisdante 。看看这个:
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秒,如果{updateButtonCount
函数在末尾包含此行,则QTimer
1}}再次超时。
我希望有所帮助。如果不清楚,请随意发表评论。