qt - PySide:QTimer 需要 QApplication 才能工作吗?

标签 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

最佳答案

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/

相关文章:

c++ - 使 QGraphicsView 大小适合

c++ - 从 QTcpSocket 读取(许多)值(快速)

python - PySide:容器类中 QGraphicsView 的事件过滤器

c++ - 我可以注册一个根据定义其类型的字符串调用特定模板函数的函数吗?

qt - 关于 Qt 中 QList<QStringList> 的问题

python - 当模型是 pandas dataframe 时使 QTableView 可编辑

python - 关闭 pySide 中的 qDialog(如果存在)

python - PySide:将标准输出重定向到对话框

python - 为什么 QFileDialog 使用斜杠而不是反斜杠?

c++ - Qt QTableWidget QDoubleSpinBoxes/QSpinBoxes 作为通过迭代访问值的元素