QThread的信号与槽用法主要涉及以下几个方面:
QThread的finished()信号
当QThread执行完毕时,会发出finished()信号。我们可以通过连接该信号到槽函数的方式,实现在QThread执行完毕后进行一些操作。
例如:
class MyThread : public QThread
{
Q_OBJECT
public:
void run() override
{
// 执行一些操作...
emit finished(); // 发出finished()信号
}
};
MyThread thread;
connect(&thread, &MyThread::finished, [=](){
qDebug() << "thread finished";
});
QThread的started()信号
当调用QThread的start()函数启动线程时,会发出started()信号。我们可以通过连接该信号到槽函数的方式,实现在线程启动前或启动后进行一些操作。
例如:
class MyThread : public QThread
{
Q_OBJECT
public:
void run() override
{
qDebug() << "thread running...";
}
};
MyThread thread;
connect(&thread, &MyThread::started, [=](){
qDebug() << "thread started";
});
thread.start();
线程间通信
由于QThread是在新线程中运行代码,因此不能直接访问主线程中的对象。为了在不同线程之间传递数据和消息,我们可以使用Qt提供的跨线程通讯机制——信号与槽。
例如,在子线程中向主界面发送消息:
class MyThread : public QThread
{
Q_OBJECT
signals:
void message(const QString& msg);
public:
void run() override
{
emit message("Hello from thread");
}
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public slots:
void handleMessage(const QString& msg)
{
qDebug() << "Received message:" << msg;
}
};
MyThread thread;
MainWindow mainWindow;
connect(&thread, &MyThread::message, &mainWindow, &MainWindow::handleMessage);
thread.start();
在上面的例子中,子线程通过发出message信号来向主线程发送消息。主界面则连接了这个信号到自己的handleMessage槽函数,以接收并处理消息。
总结:
QThread的信号与槽用法非常灵活,可以实现各种功能。需要注意的是,在使用跨线程通讯时,要确保线程安全性。
本文福利,莬费领取Qt开发学习资料包、技术视频,内容包括(C++语言基础,C++设计模式,Qt编程入门,QT信号与槽机制,QT界面开发-图像绘制,QT网络,QT数据库编程,QT项目实战,QSS,OpenCV,Quick模块,面试题等等)↓↓↓↓↓↓见下面↓↓文章底部点击莬费领取↓↓