PySide:QTimer需要QApplication才能运行?

时间:2012-02-07 20:45:12

标签: qt pyside

刚开始学习PySide并且遇到了QTimer的问题

我有这个

#!/usr/bin/python

from PySide.QtCore import QThread;
from classes import Updater;

if __name__ == "__main__":
    thread = QThread();
    thread.start();

    update = Updater();
    update.moveToThread(thread);
    update.run();

和这个

class Updater(QObject):
    def update_mode(self):
        #do something
        pass;

    def run(self):
        timer = QTimer();
        timer.timeout.connect(self.update_mode);
        timer.start(10);

我希望我的脚本能够使用QTimer定期做一些工作(想要尝试QSystemAlignedTimer,但现在看起来对我来说更复杂......)。目前还不确定是什么问题,因为我收到了这个错误

QObject::startTimer: QTimer can only be used with threads started with QThread
QEventLoop: Cannot be used without QApplication
QThread: Destroyed while thread is still running

1 个答案:

答案 0 :(得分:4)

QTimer以及所有其他基于事件的类需要有QApplication个实例。

在:

thread = QThread();
thread.start();

update = Updater();
update.moveToThread(thread);
update.run();

首先,摆脱分号。 Python程序员不喜欢这些。 如果你仔细看看你的代码在做什么,你就会创建一个QThread,启动它,创建一个Updater,将它移动到线程,运行它,然后结束程序。这里没有命令让Python保持程序运行,所以它结束了,QThread抱怨被销毁。

你应该做的是使用类似

QApplication
app = QApplication(sys.argv)

和调用app.exec_()启动它。在这种情况下,这基本上等同于time.sleep(9999999999...),但它实际上做的是它无休止地处理事件(信号/槽)。使用time.sleep(9999999999...)时,QTimers在超时时将永远不会执行任何操作。

由于QApplication是无限循环,您必须在代码中手动退出。

相关问题