Python与PyQt中的线程错误

2 投票
2 回答
3272 浏览
提问于 2025-04-15 14:22

我注意到,当在一个并行线程中执行 setModel 这个函数时(我试过使用 threading.Timer 或 threading.Thread),我得到了这个结果:

QObject: Cannot create children for a parent that is in a different thread.
(Parent is QHeaderView(0x1c93ed0), parent's thread is QThread(0xb179c0), current thread is QThread(0x23dce38)
QObject::startTimer: timers cannot be started from another thread
QObject: Cannot create children for a parent that is in a different thread.
(Parent is QTreeView(0xc65060), parent's thread is QThread(0xb179c0), current thread is QThread(0x23dce38)
QObject::startTimer: timers cannot be started from another thread

有没有什么办法解决这个问题呢?

2 个回答

0

看起来你遇到了Qt的一个限制。如果你需要让不同线程中的对象进行交流,可以试试使用信号或事件。

或者你可以去问问Qt的相关人员,这个问题似乎和PyQt没有特别的关系。

5

确实,使用Qt(以及其他复杂框架)进行多线程编程是一件非常微妙和困难的事情,需要特别的关注和小心。想了解更多,可以看看Qt的文档,里面对这个话题有很好的讲解,适合那些对线程有一定了解的人,文中也推荐了一些适合初学者的阅读材料。

如果可以的话,我建议你采用我一直推荐的Python多线程架构:让每个子系统由一个专门的线程来管理和使用;线程之间通过Queue.Queue实例进行通信,也就是通过消息传递。这种方法可能会有点限制,但它为后续的特定情况和精心设计的例外情况提供了良好的基础,比如线程池、偶尔创建新线程、锁、条件变量以及其他一些复杂的东西。对于Qt特有的内容,比如跨线程的信号/槽通信,我也会把它归类到这种情况中,可以通过排队连接来实现。

撰写回答