“你这样做是错的。” :)
尝试这个:
我的工人.h
#include ...
class MyWorker : public QObject {
Q_OBJECT
public:
explicit MyWorker(QObject* parent = 0);
public slots:
void timeConsumingMethod();
}
我的工人.cpp
#include "myworker.h"
#include ...
MyWorker::MyWorker(QObject* parent) :
QObject(parent)
{
/*
...
*/
}
void MyWorker::timeConsumingMethod() {
/*
...
*/
}
代码
/*...*/
MyWorker* worker = new MyWorker();
QThread* workerThread = new QThread();
QTimer* timer = new QTimer();
worker->moveToThread(workerThread);
worker->connect(timer, SIGNAL(timeout()), SLOT(timeConsumingMethod()));
// don't forget proper obj deletion
// not the best way, but...
worker->connect(workerThread, SIGNAL(destroyed()), SLOT(deleteLater());
workerThread->start();
timer->start(x);
在这种情况下,worker 将“生活”在 workerThread 中。QT SIGNAL-SLOT 机制支持不同线程中对象之间的连接。
通过重新实现 run() 方法和 QThread 继承,这种方法比“程序方式”要好得多
worker 工作,QThread 控制线程
来源:http: //qt-project.org/wiki/Threads_Events_QObjects