一、创建线程的过程
直接贴代码:
//1、创建线程
QThread *thread = new QThread;
//2、主要工作类
//VoiceUpdate *worker = new VoiceUpdate(this); //传参this的话,会有QObject::moveToThread: Cannot move objects with a parent
VoiceUpdate *worker = new VoiceUpdate();
//3、将工作类加入到线程
worker->moveToThread(thread);
//4、线程结束时,释放工作类
connect(thread, &QThread::finished, worker, &QObject::deleteLater);
//5、connect的第5个参数,必须是Qt::QueuedConnection
connect(thread, &QThread::started, worker, &VoiceUpdate::onStart, Qt::QueuedConnection);
connect(this, &UpdateVersion::sig_choose, worker, &VoiceUpdate::onChoose, Qt::QueuedConnection);
connect(worker, &VoiceUpdate::sig_create_gui, this, &UpdateVersion::onCreateWid, Qt::QueuedConnection);
//6、线程退出
connect(worker, &VoiceUpdate::sig_finish, this, [=]() {
thread->quit();
});
//7、开始线程运行
thread->start();
二、创建窗口-GUI
在VoiceUpdate中创建QWidget,会提示 :
ASSERT failure in QWidget: “Widgets must be created in the GUI thread.“
解决方法是:通过信号槽实现线程通讯方式,在非UI主线程发生个信号,让UI主线程调用槽函数进行相关的界面操作。connect连接方式是QueuedConnection