流程图:
工程目录图:
mythread.h:
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QImage>
class MyThread : public QObject
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
//线程处理函数
void drawImage();
signals:
void updateImage(QImage temp);
public slots:
};
#endif // MYTHREAD_H
mywidget.h:
#ifndef MYWIDGET_H
#define MYWIDGET_H
#include <QWidget>
#include "mythread.h"
#include <QThread>
namespace Ui {
class MyWidget;
}
class MyWidget : public QWidget
{
Q_OBJECT
public:
explicit MyWidget(QWidget *parent = 0);
~MyWidget();
//重写绘图事件
void paintEvent(QPaintEvent *event);
void getImage(QImage);//槽函数
void dealClose();//窗口关闭槽函数
private:
Ui::MyWidget *ui;
QImage image;
MyThread *myT;//自定义线程对象
QThread *thread;
};
#endif // MYWIDGET_H
mythread.cpp:
#include "mythread.h"
#include <QPoint>
#include <QPainter>
#include <QPen>
#include <QBrush>
MyThread::MyThread(QObject *parent) : QObject(parent)
{
}
void MyThread::drawImage()
{
//定义QImage绘图设备
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);
//定义5个点
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);
}
mywidget.cpp:
#include "mywidget.h"
#include "ui_mywidget.h"
#include <QPainter>
#include <QThread>
#include <QImage>
MyWidget::MyWidget(QWidget *parent) :
QWidget(parent),
ui(new Ui::MyWidget)
{
ui->setupUi(this);
//自定义类对象,分配空间,不可以指定父对象
myT = new MyThread ;
//创建子线程
thread = new QThread(this);
//将自定义模块添加到子线程
myT->moveToThread(thread);
//启动子线程,但是,并没有启动线程处理函数
thread->start();
//线程处理函数,必须通过sinal-slot调用
connect(ui->pushButton,&QPushButton::pressed,myT,&MyThread::drawImage);
connect(myT,&MyThread::updateImage,this,&MyWidget::getImage);
connect( this,&MyWidget::destroyed,this,&MyWidget::dealClose);
}
MyWidget::~MyWidget()
{
delete ui;
}
void MyWidget::dealClose()
{
//退出子线程
thread->quit();
//回收资源
thread->wait();
delete myT;
}
void MyWidget::getImage(QImage temp)
{
image = temp;
update();//更新窗口,间接调用paintEvent
}
void MyWidget::paintEvent(QPaintEvent *event)
{
QPainter p(this);//创建画家,指定 绘图设备为窗口
p.drawImage(50,50,image);
}
ui: