#pragma once
#include <QObject>
#include <QImage>
class QtMyThread : public QObject
{
Q_OBJECT
public:
QtMyThread(QObject *parent = nullptr);
~QtMyThread();
void drawImage();
signals:
void updateImage(QImage image);
};
#include "QtMyThread.h"
#include <QPainter>
#include <QPen>
#include <QBrush>
QtMyThread::QtMyThread(QObject *parent)
: QObject(parent)
{
}
QtMyThread::~QtMyThread()
{
}
void QtMyThread::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::red);
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);
}
#pragma once
#include <QtWidgets/QWidget>
#include "ui_QtThreadImage.h"
#include "QtMyThread.h"
class QtThreadImage : public QWidget
{
Q_OBJECT
public:
QtThreadImage(QWidget *parent = Q_NULLPTR);
void paintEvent(QPaintEvent *event);
private slots:
void slotGetImage(QImage image);
void slotDealClose();
private:
Ui::QtThreadImageClass ui;
QImage image;
QtMyThread *pmyThread;
QThread *pthread;
};
#include "QtThreadImage.h"
#include <QPainter>
#include <QThread>
QtThreadImage::QtThreadImage(QWidget *parent)
: QWidget(parent)
{
ui.setupUi(this);
pmyThread = new QtMyThread;
pthread = new QThread(this);
pmyThread->moveToThread(pthread);
pthread->start();
connect(ui.pushButton, &QPushButton::clicked, pmyThread, &QtMyThread::drawImage);
connect(pmyThread, &QtMyThread::updateImage, this, &QtThreadImage::slotGetImage);
connect(this, &QtThreadImage::destroyed, this, &QtThreadImage::slotDealClose);
}
void QtThreadImage::paintEvent(QPaintEvent *event)
{
QPainter p(this);
p.drawImage(50,50,image);
}
void QtThreadImage::slotGetImage(QImage temp)
{
image = temp;
update();
}
void QtThreadImage::slotDealClose()
{
pthread->quit();
pthread->wait();
delete pmyThread;
}