刚开始学习 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();
Run Code Online (Sandbox Code Playgroud)
和这个
class Updater(QObject):
def update_mode(self):
#do something
pass;
def run(self):
timer = QTimer();
timer.timeout.connect(self.update_mode);
timer.start(10);
Run Code Online (Sandbox Code Playgroud)
我希望我的脚本使用 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
Run Code Online (Sandbox Code Playgroud)
QTimer以及所有其他基于事件的类,需要有一个QApplication实例。
在:
thread = QThread();
thread.start();
update = Updater();
update.moveToThread(thread);
update.run();
Run Code Online (Sandbox Code Playgroud)
首先,去掉分号。Python 程序员不喜欢这些。如果你仔细看看你的代码正在做什么,你会发现你正在创建一个QThread,启动它,创建一个Updater,将它移动到线程,运行它,然后结束程序。这里没有命令告诉Python让程序保持运行,所以它结束了,并且抱怨QThread被破坏了。
你应该做的是QApplication用类似的东西制作一个
app = QApplication(sys.argv)
Run Code Online (Sandbox Code Playgroud)
app.exec_()以及启动它的调用。在这种情况下,这本质上相当于time.sleep(9999999999...),但它实际上所做的是无休止地处理事件(信号/槽)。随着time.sleep(9999999999...),QTimers超时时将永远不会执行任何操作。
由于 aQApplication是无限循环,因此您必须在代码中手动退出。