先看代码和运行效果图,如下:
#ifndef MYOBJECT_H #define MYOBJECT_H #includeclass MyObject : public QObject { Q_OBJECT public: explicit MyObject(QObject *parent = 0); protected slots: void getStarted(); void testSlot(); }; #endif // MYOBJECT_H
#include "MyObject.h" #include#include MyObject::MyObject(QObject *parent) : QObject(parent) { } void MyObject::getStarted() { qDebug() << "void MyObject::getStarted() tid = " << QThread::currentThreadId(); } void MyObject::testSlot() { qDebug() << "void MyObject::testSlot() tid = " << QThread::currentThreadId(); }
#ifndef TESTTHREAD_H #define TESTTHREAD_H #includeclass TestThread : public QThread { Q_OBJECT protected: void run(); public: explicit TestThread(QObject *parent = 0); signals: void testSignal(); protected slots: void testSlot(); }; #endif // TESTTHREAD_H
#include "TestThread.h" #includeTestThread::TestThread(QObject *parent) : QThread(parent) { connect(this, SIGNAL(testSignal()), this, SLOT(testSlot()), Qt::QueuedConnection); } void TestThread::run() { qDebug() << "void TestThread::run() -- begin tid = " << currentThreadId(); for(int i=0; i<5; i++) { qDebug() << "void TestThread::run() i = " << i; msleep(800); } emit testSignal(); exec(); qDebug() << "void TestThread::run() -- end"; } void TestThread::testSlot() { qDebug() << "void TestThread::testSlot() tid = " << currentThreadId(); }
#include#include #include #include "TestThread.h" #include "MyObject.h" int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << "main() tid = " << QThread::currentThreadId(); TestThread t; MyObject m; QObject::connect(&t, SIGNAL(started()), &m, SLOT(getStarted()), Qt::QueuedConnection); QObject::connect(&t, SIGNAL(testSignal()), &m, SLOT(testSlot()), Qt::QueuedConnection); m.moveToThread(&t); t.start(); return a.exec(); }
运行结果图:
对象m通过moveToThread函数更改了对象的线程依附性(更改为依附于线程对象t), 而对象t没有更改线程的依附性(依附于主线程),所以t对象中的槽函数是由主函数所调用,对象m中的槽函数是由线程t调用执行的。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)