目标:创建一个子线程,同时在子线程中完成绘图,再在主线程中显示子线程所绘制的图像
创建一个继承QObject的类
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QImage>
class mythread : public QObject
{
Q_OBJECT
public:
explicit mythread(QObject *parent = nullptr);
//线程处理函数
void drawimage();
signals:
void updateimage(QImage);
public slots:
};
#endif // MYTHREAD_H
#include "mythread.h"
#include <QPainter>
#include <QPen>
#include <QBrush>
mythread::mythread(QObject *parent) : QObject(parent)
{
}
void mythread::drawimage()
{
QImage image(500,500,QImage::Format_ARGB32);
QPainter p(&image);
QPen pen;
pen.setWidth(5);
p.setPen(pen);
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(Qt::red);
p.setBrush(brush);
QPoint a[]
{
QPoint(qrand()%500,qrand()%500),
QPoint(qrand()%500,qrand()%500),
QPoint(qrand()%500,qrand()%500),
QPoint(qrand()%500,qrand()%500),
QPoint(qrand()%500,qrand()%500),
};
//画多边形
p.drawPolygon(a,5);
//通过信号发送图片
emit updateimage(image);
}
#ifndef WIDGET_H
#define WIDGET_H
#include <QWidget>
#include "mythread.h"
#include <QThread>
#include <QImage>
namespace Ui {
class Widget;
}
class Widget : public QWidget
{
Q_OBJECT
public:
explicit Widget(QWidget *parent = 0);
~Widget();
void paintEvent(QPaintEvent *event);
void getimage(QImage);
void dealclose();//窗口关闭槽函数
private:
Ui::Widget *ui;
QImage image;
mythread *myt;
QThread *thread;
};
#endif // WIDGET_H
#include "widget.h"
#include "ui_widget.h"
#include <QPainter>
#include <QImage>
#include <QThread>
Widget::Widget(QWidget *parent) :
QWidget(parent),
ui(new Ui::Widget)
{
ui->setupUi(this);
//自定义线程对象,不可以指定父对象
myt=new mythread;
//创建子线程
thread=new QThread(this);
//把自定义模块添加到子线程
myt->moveToThread(thread);
thread->start();
//线程处理函数只能信号和槽处理
connect(ui->pushButton,&QPushButton::pressed,myt,&mythread::drawimage);
connect(myt,&mythread::updateimage,this,&Widget::getimage);
connect(this,&Widget::destroyed,this,&Widget::dealclose);
}
Widget::~Widget()
{
delete ui;
}
void Widget::getimage(QImage temp)
{
image =temp;
update();//间接调用重绘
}
void Widget::paintEvent(QPaintEvent *event)
{
QPainter p(this);
p.drawImage(50,50,image);
}
void Widget::dealclose()
{
thread->quit();
thread->wait();
delete myt;
}
相比于直接在主线程中进行操作,可以避免在数据处理时无法进行其他操作的现象。
实现效果: