moveToThread的最简单用法(依葫芦画瓢即可)(使得线程也更偏向于信号槽的使用方法)

/*!
* file main.cpp
*
* Copyright (C) 2010, dbzhang800
* All rights reserved.
*
*/
#include <QtCore/QCoreApplication> 
#include <QtCore/QObject> 
#include <QtCore/QThread> 
#include <QtCore/QDebug> 
 
class Dummy:public QObject 
{ 
    Q_OBJECT 
public: 
    Dummy(QObject* parent=0):QObject(parent)     {} 
public slots: 
    void emitsig() 
    { 
        emit sig(); 
    } 
signals: 
    void sig(); 
}; 
 
class Object:public QObject 
{ 
    Q_OBJECT 
public: 
    Object(){} 
public slots: 
    void slot() 
    { 
        qDebug()<<"from thread slot:" <<QThread::currentThreadId(); 
    } 
}; 
 
#include "main.moc" 
 
int main(int argc, char *argv[]) 
{ 
    QCoreApplication a(argc, argv); 
    qDebug()<<"main thread:"<<QThread::currentThreadId(); 
    QThread thread; 
    Object obj; 
    Dummy dummy; 
    obj.moveToThread(&thread); 
    QObject::connect(&dummy, SIGNAL(sig()), &obj, SLOT(slot())); // 这里的slot()函数,相当于run()函数的作用
    thread.start(); 
    dummy.emitsig(); 
    return a.exec(); 
}

        结果:恩,slot确实不在主线程中运行(这么简单不值得欢呼么?)

main thread: 0x1a5c 
from thread slot: 0x186c

http://blog.csdn.net/zzwdkxx/article/details/49308487
原文地址:https://www.cnblogs.com/findumars/p/5804938.html