刚刚开始学习 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
最佳答案
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
是一个无限循环,因此您必须在代码中手动退出。
关于qt - PySide:QTimer 需要 QApplication 才能工作吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9183606/