2013-04-17 71 views
1

簡單的問題:是否可以從QThread中分離QObject以將其移至主線程?從線程中分離對象

我使用下面的代碼:

QThread *thread = new QThread(); 

MyObject *object = new MyObject(); 

object->moveToThread(thread); 

thread->start(); 

而且地方後,我想將MyObject實例移動到主線程。

object->moveToThread(QApplication::instance()->thread()); 

我有以下錯誤:QObject::moveToThread: Current thread (0x00000001) is not the object's thread (0x00000002). Cannot move to target thread (0x00000003)

感謝

回答

1

隨着official doc saysmoveToThread功能不能從另一個線程「拉」的對象,它「推」的對象到另一個線程。

這就是爲什麼如果你想改變你的對象的線程親和力,你應該在當前對象的線程中做到這一點。

我已經添加了一個簡單的例子。

這裏的Worker類:

class Worker : public QObject 
{ 
    Q_OBJECT 
public: 
    explicit Worker(QObject *parent = 0); 
signals: 
    void done(); 

public slots: 
    void doWork(); 
    void checkThread(); 

private: 
    bool isMainThread(); 
}; 

Worker::Worker(QObject *parent) : 
    QObject(parent) 
{ 
    qDebug() << __PRETTY_FUNCTION__ 
      << QThread::currentThread() 
      << isMainThread(); 
} 

void Worker::doWork() 
{ 
    qDebug() << __PRETTY_FUNCTION__ 
      << QThread::currentThread() 
      << isMainThread(); 

    qDebug() << __PRETTY_FUNCTION__ << "Work is done"; 
    moveToThread(qApp->thread()); 
    emit done(); 
} 

void Worker::checkThread() 
{ 
    qDebug() << __PRETTY_FUNCTION__ 
      << QThread::currentThread() 
      << isMainThread(); 
} 

bool Worker::isMainThread() 
{ 
    return QThread::currentThread() == qApp->thread(); 
} 

我們創建了一個Worker對象,QThread對象,它們相互連接:

QThread *thread = new QThread; 
Worker *worker = new Worker; 
worker->moveToThread(thread); 

QObject::connect(thread, SIGNAL(started()), worker, SLOT(doWork())); 
QObject::connect(worker, SIGNAL(done()), thread, SLOT(quit())); 
QObject::connect(thread, SIGNAL(finished()), worker, SLOT(checkThread())); 
QObject::connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater())); 

thread->start(); 

這就是我們在應用程序的輸出了:

Worker::Worker(QObject*) QThread(0x1034680) true 
void Worker::doWork() QThread(0x1224970) false 
void Worker::doWork() Work is done 
void Worker::checkThread() QThread(0x1034680) true 

A Worker對象正在主應用程序線程中創建,然後它在新線程中完成其工作。作業完成後,它會發送done()信號並將其自身移回主線程。線程完成後,我們檢查我們的Worker對象現在是否真的再次位於主線程中。

但我真的不明白爲什麼你可能需要這個。

+0

好吧,但如何做到這一點?只需用新線程調用'moveToThread'? – Maxbester

+0

在你的示例中做類似的事情,但首先啓動線程,然後調用moveToThread方法。 –

+0

我更新了問題。我嘗試將對象移回主線程。但是結果相同... – Maxbester