【发布时间】:2012-03-25 17:08:00
【问题描述】:
首先,我对 Python 和 Pyside 非常陌生。为了做一些自我改进,我试图让 QTimer 在我的 PySide 程序的子线程中每秒执行一次(目前我只希望它每秒打印“hi!”到终端不冻结主窗口)。
我尝试将 example I found on the Qt Wiki 从 C++ 转换为 Python/PySide,但由于我并不真正了解 C++,因此我假设我将其转换错误,这就是它无法正常工作的原因。
目前,doWork() 函数似乎只执行一次,然后再也不会执行。我究竟做错了什么?有没有更好的方法在 PySide 中每秒执行一个函数而不冻结主窗口?
这里是代码(我删除了一些主窗口代码以增加清晰度):
from PySide import QtGui
from PySide import QtCore
from client_gui import Ui_MainWindow
statsThread = QtCore.QThread()
class MainWindow(QtGui.QMainWindow, Ui_MainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
#setup GUI
self.setupUi(self)
#start thread to update GUI
self.statsThread = updateStatsThread()
self.statsThread.start(QtCore.QThread.TimeCriticalPriority)
class updateGuiWithStats(QtCore.QObject):
def Worker(self):
timer = QtCore.QTimer()
timer.timeout.connect(self.doWork())
timer.start(1000)
def doWork(self):
print "hi!"
class updateStatsThread (QtCore.QThread):
def run(self):
updater = updateGuiWithStats()
updater.Worker()
self.exec_()
if __name__ == '__main__':
app = QtGui.QApplication(sys.argv)
frame = MainWindow()
frame.show()
sys.exit(app.exec_())
【问题讨论】: