Qt 线程初识别

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 = ); //线程处理函数
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(,,QImage::Format_ARGB32); QPainter p(&image); QPen pen;
pen.setWidth();
p.setPen(pen);
QBrush brush;
brush.setStyle(Qt::SolidPattern);
brush.setColor(Qt::blue);
p.setBrush(brush); QPoint a[] = { QPoint(qrand()%,qrand()%),
QPoint(qrand()%,qrand()%),
QPoint(qrand()%,qrand()%),
QPoint(qrand()%,qrand()%),
QPoint(qrand()%,qrand()%) }; p.drawPolygon(a,); 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 = );
~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();
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(,,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();
}
上一篇:MyBatis 源码分析 - 缓存原理


下一篇:EC读书笔记系列之18:条款47、48