qt文档关于QT QThread类介绍的第一句话就是:
The QThread class provides a platform-independent way to manage threads.QThread类提供了一种与平台无关的线程管理方法。
QThrea不是线程,不是线程,是管理线程的类。
要想提高编程能力,还得多看文档且理解文档内容。
Thread Affinity
A QObject instance is said to have a thread affinity, or that it lives in a certain thread.一个QObject实例具有线程关联的特性,或者或它本身就位于某个线程中
When a QObject receives a queued signal or a posted event, the slot or event handler will run in the thread that the object lives in.当QObject收到排队信号或发布的事件时,槽函数或事件处理程序将在对象所在的线程中运行。也就是说,要想槽函数或者事件处理程序在对象所处的线程运行,必须用信号或事件来触发运行,否则其会在父对象的线程运行。
class A: public QObject
{
Q_OBJECT
public slot:
void doSomething();
}
class B: public QObject
{
Q_OBJECT
A a;
QThread thread = new QThread;
a.moveToThread(thread);
thread.start();
connect(this, &B::sig_doSomething, a, &A::doSomething);
a.doSomething(); //doSomething()函数是在B类线程下执行
emit sig_doSomething();//信号触发,此时doSomething()函数是在thread下执行
}
Note: If a QObject has no thread affinity (that is, if thread() returns zero), or if it lives in a thread that has no running event loop, then it cannot receive queued signals or posted events.如果QObject 没有线程关联或者thread()返回0,这个对象没有运行的事件循环,不能接收队列信号或发布的事件。
By default, a QObject lives in the thread in which it is created. An object's thread affinity can be queried using thread() and changed using moveToThread().默认情况下,QObject位于创建它的线程中。可以使用thread()查询对象的线程相关性,并使用moveToThread()改变其所处线程。
All QObjects must live in the same thread as their parent. Consequently:
- setParent() will fail if the two QObjects involved live in different threads.
- When a QObject is moved to another thread, all its children will be automatically moved too.当一个QObject被移动到另一个线程时,它的所有子对象也将自动移动。
- moveToThread() will fail if the QObject has a parent.如果QObject有父对象,则moveToThread()将失败。
QTimer* m_sendTimer = NULL;
m_sendTimer = new QTimer;
m_sendTimer->moveToThread(this->thread()); //成功的
QTimer* m_sendTimer = NULL;
m_sendTimer = new QTimer(this);
m_sendTimer->moveToThread(this->thread()); //失败的
- If QObjects are created within QThread::run(), they cannot become children of the QThread object because the QThread does not live in the thread that calls QThread::run().
Note: A QObject's member variables do not automatically become its children. The parent-child relationship must be set by either passing a pointer to the child's constructor, or by calling setParent(). Without this step, the object's member variables will remain in the old thread when moveToThread() is called.
QObject的成员变量不会自动成为其子变量。必须通过传递指向子构造函数的指针或调用setParent()来设置父子关系。如果没有这个步骤,当调用moveToThread()时,对象的成员变量将保留在旧线程中。