回复: Qt的多线程是不是不能使用QTimer
#6 回 沉默小ai 的帖子 [wcrqpdb 11-07 11:32]
沉默小ai:你实在是想用继承QThread的方式的话,把QTimer 的对象在run函数内创建,这样这个QTimer就属于这个线程了,继承的Qthread的类的创建、构造函数的实际上还是由 创建 继承的Qthread的类 的线程操作的。 (2019-11-07 11:23)
在run内创建也不行,报QObject: Cannot create children for a parent that is in a different thread.
(Parent is readWriteThread(0x21080b80), parent's thread is QThread(0x20fd2530), current thread is readWriteThread(0x21080b80)
#7 回 wcrqpdb 的帖子 [angelus 11-07 11:39]
wcrqpdb:在run内创建也不行,报QObject: Cannot create children for a parent that is in a different thread.
(Parent is readWriteThread(0x21080b80), parent's thread is QThread(0x20fd2530), current thread is readWriteThread(0x21080b80)
(2019-11-07 11:32)
这个报错应该和qtimer无关,QTimer是可以直接实例化在run函数内,不过建议把QTimer包含进一个类中,所有run 中运行的逻辑都在这个类中实现,这样,run函数会很干净,多线程操作也会很有条理性
#8 [圣域天子 11-07 11:48]
Qt大量控件都存在这个跨线程问题,只能在单个线程中使用。
#9 回 angelus 的帖子 [uidab 11-07 13:57]
angelus:这个报错应该和qtimer无关,QTimer是可以直接实例化在run函数内,不过建议把QTimer包含进一个类中,所有run 中运行的逻辑都在这个类中实现,这样,run函数会很干净,多线程操作也会很有条理性 (2019-11-07 11:39)
#10 回 wcrqpdb 的帖子 [uidab 11-07 13:59]
wcrqpdb:在run内创建也不行,报QObject: Cannot create children for a parent that is in a different thread.
(Parent is readWriteThread(0x21080b80), parent's thread is QThread(0x20fd2530), current thread is readWriteThread(0x21080b80)
(2019-11-07 11:32)
没代码不好评论,记住这种方式只有在run()中的才是另一个线程。所以你的QTimer变量也只能在这里实例化。很多人是在继承QThread的类定义了QTimer的成员变量,以为这个也是在另一个线程,其实不是。