我试图为处理该特定类的所有事件的Scanner类创建一个线程,从而释放GUI线程。我在GUI上有一个退出按钮,该按钮仅调用qApp-> quit()退出应用程序,但是我不确定如何处理Scanner类中的线程。退出应用程序时,我在调试日志中看到以下错误。
QThread::wait: Thread tried to wait on itself
QThread::wait: Thread tried to wait on itself
QThread: Destroyed while thread is still running
在Scanner.cpp中(省略其他功能)
Scanner::Scanner() :
{
this->moveToThread(&m_thread);
connect(&m_thread, &QThread::finished, this, &QObject::deleteLater);
connect(this, SIGNAL(StartEnroll()), this, SLOT(StartEnrollment()));
m_thread.start();
}
Scanner::~Scanner()
{
m_thread.quit(); // Not sure if this is the correct
m_thread.wait();
}
在主Window.cpp中(省略其他功能)
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
connect(ui->ExitButton, SIGNAL(released()), this, SLOT(Quit()));
connect(&m_scanner, SIGNAL(FinishedEnroll(bool)), this, SLOT(EnrollDone(bool)));
}
void MainWindow::Quit()
{
close();
qApp->quit();
}
任何有关如何退出的指针都会安全退出多线程应用程序中的应用程序。
您需要让Scanner
类知道该应用程序正在退出。
将以下行添加到的构造函数中 MainWindow
connect(qApp, SIGNAL(aboutToQuit()), &m_scanner, SLOT(deleteLater()));
更新:
connect(&m_thread, &QThread::finished, this, &QObject::deleteLater);
不应该在构造函数中 Scanner
和
m_thread.quit();
m_thread.wait();
不应该在 Scanner
实际上,m_thread
不应Scanner
以任何方式参与其中。本QThread
类并不代表一个线程,它是一个线程管理器,应拥有并从那里创建它的线程控制。
在Qt中有多种使用线程的方法,很多方法没有很好地记录。如果您想使用
workerObject->moveToThread(&thread);
thread.start();
使用线程的方式,m_thread
则应成为MainWindow
类的成员,并且这些函数调用应在其构造函数中进行。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句