学习目的:将 Qt的UI界面控制 和 TCP连接通信 分离,提高Qt客户端运行效率。
使用方法:直接启动、移动至线程、调用线程函数
方法1:直接启动线程
(1)创建继承QThread的类
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
Q_OBJECT
protected:
void run() override { // 启动线程后自动调用 run() 函数
// 线程要执行的任务
...
...
}
};
(2)主线程中创建并启动线程
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
MyThread *thread = new MyThread();
thread->start(); // 启动线程,自动执行 run()函数
return a.exec();
}
方法2:将QObject类的对象移到 线程 中运行( moveToThread( ) 函数)
(1)创建继承 QObject 的 Worker 类
#include <QObject>
class Worker : public QObject
{
Q_OBJECT
public:
void doWork() {
...
...
}
};
(2)将 Worker 类移到 QThread 线程中运行
#include <QCoreApplication>
#include <QThread>
#include <QObject>
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建线程对象
QThread *thread = new QThread();
// 创建工作对象
Worker *worker = new Worker();
// 将工作对象移到子线程中
worker->moveToThread(thread);
connect(thread, &QThread::started, worker, &Worker::doWork);
// 启动子线程
thread->start();
return a.exec();
}
方法3(改进2):将QObject类的对象移到 自定义线程 中运行
(1)定义 WorkerThread 线程类
#include <QObject>
class WorkerThread : public QThread
{
Q_OBJECT
public:
WorkerThread (QObject *parent = nullptr) : QThread(parent){
worker = new Worker();
worker->moveToThread(this);
}
void run() override{
exec();
}
~WorkerThread() {
delete worker;
}
private slots:
void doWork(){
worker->doWork();
}
private:
Worker *worker;
};
(2)调用 WorkerThread 槽函数 doWork()
#include <QCoreApplication>
#include "WorkerThread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
// 创建 WorkerThread 实例
WorkerThread *workerThread = new WorkerThread();
connect(workerThread, &WorkerThread::started, workerThread, &WorkerThread::doWork); // 启动线程时执行 doWork
// 启动线程
workerThread->start();
return a.exec(); // 启动事件循环
}
方法4:利用invokeMethod直接调用线程内部函数
#include <QCoreApplication>
#include <QThread>
#include "WorkerThread.h"
int main(int argc, char *argv[])
{
QCoreApplication a(argc, argv);
WorkerThread *workerThread = new WorkerThread();
workerThread->start();
// 通过 QMetaObject::invokeMethod 调用 doWork(),并指定在 workerThread 所在的线程中执行
QMetaObject::invokeMethod(workerThread, "doWork", Qt::QueuedConnection);
return a.exec();
}
如果要传参数
QString data = "Hello, Server!";
QMetaObject::invokeMethod(ServerConnectThread::instance(), "initConnect", Qt::QueuedConnection, Q_ARG(QString, data));
先写这些,深入学习后再添加