1. Qt中子线程直接操作界面组件会怎么样?
标题为什么叫“多线程与界面组件地通信?”线程难道不能直接刷界面,非要搞成对立地两方,通过某种方式通信?先看一段代码,在子线程中新建widget 界面:
以下是threadWidget.h//
#ifndef THREADWIGHT_H
#define THREADWIGHT_H
#include <QObject>
#include <QWidget>
#include "QThread"
class threadWight : public QThread
{
public:
threadWight();
protected:
void run();
};
#endif // THREADWIGHT_H
以下是threadWidget.cpp//
#include "threadwight.h"
threadWight::threadWight()
{
}
void threadWight::run()//在新线程中创建一个窗口,并显示出来
{
QWidget w;
w.show();
exec();
}
以下是main函数//
#include "widget.h"
#include <QApplication>
#include "threadwight.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
threadWight * widgetThread = new threadWight;
widgetThread->start();//开启线程,子线程中新建窗口并显示
return a.exec();
}
可以想象得到代码运行会有问题,不然界面直接在子线程中新建、刷新就好了,也不用谈什么通信了。看看运行结果:
编译输出“
Widgets must be created in the GUI thread
”,窗口必须新建在GUI线程中,GUI线程就是主线程,main函数进来地线程。我们不禁有疑问,为什么必须只能在主线程中操作界面组件,而不能在子线程中进行操作呢? 现代地GUI平台经过多年发展,渐渐总结经验教训,将很多容易导致问题地做法禁止,以保证执行时更安全可靠,显然,只准在主线程中操作GUI组件,不仅仅时Qt一个平台做出地改变,其他成熟平台也做了这样地规定。
- 我们在Qt编程中尤其要注意,不要多此一举在子线程中直接操作界面组件,也有几种办法能够做到勉强操作,但都是不安全、不可靠地。
2. Qt中子线程怎样间接操作界面?
“间接”二字道出核心,只能通过某种途径实现线程和界面组件地通信,传递要更新地信息。Qt提供地信号与槽机制,就能很好地实现这样地需求:子线程中发射信号,信号中带有更新信息,主线程中地槽来操作界面组件。这里用到信号与槽跨线程了,要用异步方式连接。看一段示例代码:
///以下时main.cpp
#include "widget.h"
#include <QApplication>
#include "threadwight.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Widget w;
w.show();
return a.exec();
}
/以下时线程类的声明和实现/
#ifndef THREADWIGHT_H
#define THREADWIGHT_H
#include <QObject>
#include <QWidget>
#include "QThread"
class threadWight : public QThread
{
Q_OBJECT
public:
threadWight();
protected:
void run();
signals:
void sigUpdateInfo(QString info);//子线程中地信号,给出要更新地信息
private:
};
#endif // THREADWIGHT_H
//
#include "threadwight.h"
threadWight::threadWight()
{
}
void threadWight::run()
{
emit sigUpdateInfo("thread start");
for(int i = 0;i<10;i++)
{
msleep(100);
emit sigUpdateInfo(QString::number(i));
}
emit sigUpdateInfo("thread end");
}
///以下是窗口类的声明和实现
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "QPlainTextEdit"
#include "threadwight.h"
class Widget : public QWidget
{
Q_OBJECT
public:
Widget(QWidget *parent = nullptr);
~Widget();
private:
QPlainTextEdit *plainText;
private slots:
void slotUpdatePlainText(QString info);
};
#endif // WIDGET_H
//
#include "widget.h"
Widget::Widget(QWidget *parent)
: QWidget(parent)
{
this->resize(300,300);
plainText = new QPlainTextEdit(this);
plainText->resize(300,300);
threadWight * widgetThread = new threadWight;
connect(widgetThread,SIGNAL(sigUpdateInfo(QString)),this,SLOT(slotUpdatePlainText(QString)));
widgetThread->start();
}
void Widget::slotUpdatePlainText(QString info)
{
plainText->appendPlainText(info);
}
Widget::~Widget()
{
}
示例代码中,通过子线程中发射信号,来告诉主线程的槽,要更新信息了。看一下运行结果:
运行结果达到了我们的要求。Qt中还有另一种方式可以达到同样的效果,将在下一节中介绍一下。
原创内容,禁止转载
王雄 2021.03.11首次更新