这样的事情怎么样?
class Worker
{
//note, only pass parameters by copy here.
public:
Worker(int param) : myParam(param) {}
public slots:
void process()
{
//do something with myParam here, it will run in the thread.
}
signals:
void finished();
void error(QString err);
private:
int myParam;
};
然后可以使用“moveToThread”将其连接到线程对象,如下所示:
QThread* thread = new QThread;
Worker* worker = new Worker(5);
worker->moveToThread(thread);
connect(worker, SIGNAL(error(QString)), this, SLOT(errorString(QString)));
connect(thread, SIGNAL(started()), worker, SLOT(process()));
connect(worker, SIGNAL(finished()), thread, SLOT(quit()));
connect(worker, SIGNAL(finished()), worker, SLOT(deleteLater()));
connect(thread, SIGNAL(finished()), thread, SLOT(deleteLater()));
thread->start();
有关 Qt 中线程使用的更多信息和简短教程,请参见此处:http:
//mayaposch.wordpress.com/2011/11/01/how-to-really-truly-use-qthreads-the-full-explanation/