Qt 多线程示例

本文提供了一个Qt中实现多线程的示例代码,包括了创建线程、消息传递及停止线程的方法。该示例展示了如何在CThread类中进行图像处理,并通过继承QThread来实现线程安全的操作。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值