- 需要实现虚函数run()
The thread does not begin executing until start() is called.
start() begins execution of the thread by calling run().
run() The starting point for the thread. After calling start(), the newly created thread calls this function. The default implementation simply calls exec().
A QThread object manages one thread of control within the program. QThreads begin executing in run(). By default, run() starts the event loop by calling exec() and runs a Qt event loop inside the thread.
You can use worker objects by moving them to the thread using QObject::moveToThread().
Protected Functions:
int exec()
virtual void run()
Public Slots:
void exit(int returnCode = 0)
void quit()
void start(QThread::Priority priority = InheritPriority)
void terminate()
class WorkerThread : public QThread
{
Q_OBJECT
void run() override {
QString result;
/* ... here is the expensive or blocking operation ... */
emit resultReady(result);
}
signals:
void resultReady(const QString &s);
};
void MyObject::startWorkInAThread()
{
WorkerThread *workerThread = new WorkerThread(this);
connect(workerThread, &WorkerThread::resultReady, this, &MyObject::handleResults);
connect(workerThread, &WorkerThread::finished, workerThread, &QObject::deleteLater);
workerThread->start();
}
In that example, the thread will exit after the run function has returned. There will not be any event loop running in the thread unless you call exec().
- [slot] void QThread::terminate()
erminates the execution of the thread. The thread may or may not be terminated immediately, depending on the operating system’s scheduling policies. Use QThread::wait() after terminate(), to be sure.
Warning: This function is dangerous and its use is discouraged. The thread can be terminated at any point in its code path