我正在尝试创建一个单独的线程来处理数据,然后将其传递回主线程。这是我正在考虑做的事情:
class Worker : public Object
{
Q_BOJECT
public:
Worker(){
QThread* thread = new QThread;
this->moveToThread(thread);
};
~Worker();
DataClass* data1;
int data2
QThread* thread;
public slots:
void process(){
//do something to create DataClass* data1 and int Data2
moveToThread(QApplication::instance()->thread());
Q_EMIT ImDone(this);
};
signals:
void ImDone(Worker * data);
}
class MainWin : public QMainWindow
{
Q_BOJECT
public:
MainWin(){
QTreeWidget* tree=new QTreeWidget();
};
~MainWin();
void callWorker(){
Worker* worker = new Worker();
connect(this, SIGNAL(startWorker()), worker, SLOT(process()));
connect(worker, SIGNAL(ImDone(Worker *)), this, SLOT(processWorkerResult(Worker *)));
Q_EMIT startWorker();
};
QTreeView* tree;
public slots:
void processWorkerResult(Worker *worker){
//process Worker data1 and data2, update QTreeWidget* tree
};
signals:
void startWorker();
}
这种想法是,我在主线程中创建了工作线程,通过向其发送信号(MainWin :: startWorker())启动工作线程,工作线程开始工作,然后发送带有指向数据指针的信号(Worker :: ImDone(Worker *))返回主线程。然后主线程处理数据并更新其组件(例如QTreeWidget)。这样看起来还好吗?
有人可以解释一下在主线程中如何处理信号/插槽事件吗?如果用户启动两个不同的工作程序,这些工作程序最终同时(字面意义上)完成,是否会导致彼此同时运行MainWin :: processWorkerResult的两个实例?如果是这样,那似乎是一个问题...谢谢。