在继承自QThread时,于run()函数中使用定时器QTimer的注意事项
- 不能在构造函数(不在run()函数之中)中创建QTimer,而在run()中执行start()
错误输出:
QObject::startTimer: Timers cannot be started from another thread
- 在run()函数中可以将QTimer创建在栈上,若是创建在堆上,则不能指定父对象
若指定父对象,则会有错误输出:
QObject: Cannot create children for a parent that is in a different thread.
(Parent is WorkThread(0x7efe30), parent’s thread is QThread(0x1af1430), current thread is WorkThread(0x7efe30)
- 在为QTimer连接的槽函数为lambda时,若指定接收者为this,则槽函数于主线程运行;若想槽函数于子线程运行,则不指定接收者
- 在run()函数最后使用exec()来开启线程的事件循环