流程圖:
工程目錄圖:
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: