qt中多线程使用示例:
.h文件:
#ifndef CTHREAD_H
#define CTHREAD_H
#include <QThread>
#include <QImage>
class CThread : public QThread
{
Q_OBJECT
public:
CThread();
void setMessage(QString message);
void stop();
void SetImage(const QImage& img);
QImage& GetShowImage();
protected:
void run();
void printMessage();
void CreateShowImage();
private:
QString messageStr;
QImage m_image;
QImage m_showImage;
volatile bool stopped;
};
#endif // CTHREAD_H
.cpp文件:
#include "CThread.h"
#include <QDebug>
#include <QPainter>
CThread::CThread()
{
stopped = false;
}
void CThread::run()
{
while(!stopped)
{
CreateShowImage();
}
stopped = false;
}
void CThread::stop()
{
stopped = true;
}
void CThread::setMessage(QString message)
{
messageStr = message;
}
void CThread::printMessage()
{
qDebug()<<messageStr;
sleep(1);
}
QImage& CThread::GetShowImage()
{
return m_showImage;
}
void CThread::SetImage( const QImage& img )
{
m_image = img;
}
void CThread::CreateShowImage()
{
int nWidth = m_image.width();
int nHeight = m_image.height();
if (nWidth <=0||nHeight<=0)
{
//stopped = true;
return;
}
m_showImage = QImage(3*nWidth,3*nHeight,QImage::Format_ARGB32);
QPainter painter(&m_showImage);
QPixmap pixmap;
pixmap.convertFromImage(m_image);
for (int i=0;i<3;++i)
{
painter.drawPixmap(0+i*nWidth,0,pixmap);
painter.drawPixmap(0+i*nWidth,nHeight,pixmap);
painter.drawPixmap(0+i*nWidth,2*nHeight,pixmap);
}
//stopped = true;
}