你不能打电话
doWork()
因此,触发辅助线程执行工作的正确方法是以下连接:
connect(&_nfcThread, &QThread::started, &_nfc, &MyNfc::doWork);
嫁妆
.
deleteLater()
deleteLater()
_nfc.moveToThread(&_nfcThread);
connect(&_nfcThread, &QThread::started, &_nfc, &MyNfc::doWork); // this starts the worker
connect(&_nfc, &MyNfc::resultRead, this, &MyProject::nfc_readResult); // this passes the result
connect(&_nfc, &MyNfc::resultRead, &_nfcThread, &QThread::quit); // this will quit the event loop in the thread
_nfcThread.start();
更新:如果要定期调用插槽,请连接计时器。当工作完成时,不要退出线程。最简单的情况是:
_nfc.moveToThread(&_nfcThread);
connect(&_nfcThread, &QThread::started, &_timer, &QTimer::start); // this starts the timer after the thread is ready
connect(&_timer, &QTimer::timeout, &_nfc, &MyNfc::doWork); // start work at timer ticks
connect(&_nfc, &MyNfc::resultRead, this, &MyProject::nfc_readResult); // this passes the result
_nfcThread.start();
但是,由于没有退出事件循环,因此需要在删除线程之前手动退出它。最好的位置是在主类的析构函数中。
MainClass::~MainClass()
{
_nfcThread.quit(); // this schedules quitting of the event loop when the thread gets its current work done
_nfcThread.wait(); // this waits for it, this is important! you cannot delete a thread while it is working on something.
// ... because the thread (and the worker too) will get deleted immediately once this destructor body finishes, which is... right now!
}