1. 程式人生 > >Qt 線程初識別

Qt 線程初識別

argv etc mes private format 線程 set ots main.c

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();
}

Qt 線程初識別