Qt有两种多线程的方法,其中一种是继承QThread的run函数,另外一种是把一个继承于QObject的类转移到一个Thread里。
这里我使用的是继承的方法使用线程花一个"复杂"图片的例子:
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
myThread.cpp
#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::blue); 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); }
widget.h
#ifndef WIDGET_H #define WIDGET_H #include <QWidget> #include <QThread> #include <Qimage> #include "myThread.h" namespace Ui { class Widget; } class Widget : public QWidget { Q_OBJECT public: explicit Widget(QWidget *parent = 0); ~Widget(); void paintEvent(QPaintEvent *); void getImage(QImage temp); //槽函数 void dealClose(); private: Ui::Widget *ui; QImage image; myThread *myT; QThread *thread2; }; #endif // WIDGET_H
widget.cpp
#include "widget.h" #include "ui_widget.h" #include <QPainter> #include <QTimer> Widget::Widget(QWidget *parent) : QWidget(parent), ui(new Ui::Widget) { ui->setupUi(this); myT = new myThread; thread2 = new QThread(this); myT->moveToThread(thread2); thread2->start(); QTimer *timer = new QTimer(this); timer->start(100); connect(timer,&QTimer::timeout,myT,&myThread::drawImage); connect(ui->pushButton,&QPushButton::pressed,myT,&myThread::drawImage); connect(myT,&myThread::updateImage,this,&Widget::getImage); connect(this,&Widget::destroyed,this,&Widget::dealClose); } void Widget::dealClose() { thread2->quit(); thread2->wait(); thread2->deleteLater(); } Widget::~Widget() { delete ui; } void Widget::getImage(QImage temp) { image = temp; update(); } void Widget::paintEvent(QPaintEvent *) { QPainter p(this); p.drawImage(50,50,image); }
main.cpp
#include "widget.h" #include <QApplication> int main(int argc, char *argv[]) { QApplication a(argc, argv); Widget w; w.show(); return a.exec(); }