2021-07-20qt子线程做累加,每加一个数sleep50ms,用进度条显示累加的进度,可以用按钮控制暂停和继续


MyThread.h头文件

#ifndef MYTHREAD_H
#define MYTHREAD_H
#pragma execution_character_set("utf-8")

#include<QThread>
#include<QMutex>
#include<QDebug>
#include<QWaitCondition>
class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr);
    //析构函数
    ~MyThread();

     //暂停函数
    void pause();
    //继续函数
    void resume();
    //停止函数
    void stop();
    void start();
    //是否暂停 false 为暂停 true为未暂停
    bool m_isPause;
    //是否停止,false为未停止,true为停止
    bool m_isStop;
    //总和
    int m_sum=0;

protected:
    void run();//线程处理函数,通过start()间接调用
signals:
    void updateProgress(const int n,int num);
private:

};

#endif // MYTHREAD_H
MyThread.cpp
#include "mythread.h"

MyThread::MyThread(QObject *parent) : QThread(parent)
{

}

MyThread::~MyThread()
{

}

//线程处理函数
void MyThread::run()
{
    qDebug()<<"进入子线程:"<<QThread::currentThread();
    m_isPause=false;
    int i=0;
    int n=0;
    while(true)
    {
        if (m_isStop)
        {
            i=0;
            this->m_sum=0;
            break;
        }
        if(m_isPause)
        {
            continue;
        }
        i++;
        qDebug()<<i;
        this->msleep(50);
        this->m_sum+=i;
        emit updateProgress(n,i);
        qDebug()<<"子线程号:"<<QThread::currentThread();
        qDebug() << "退出子线程 : " << QThread::currentThread();
    }
}

//暂停函数
void MyThread::pause()
{
    if (QThread::isRunning())
    {
        this->m_isPause=true;
    }
}
//继续函数
void MyThread::resume()
{
    if (QThread::isRunning())
    {
    this->m_isPause=false;
    }
}

void MyThread::stop()
{
    m_isStop=true;
    QThread::quit();
    QThread::wait();
}

void MyThread::start()
{
    m_isStop=false;
    QThread::start();
}

widget.h

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include"mythread.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

    //
    void dealCalc(int n,int num);
    void stopThread();


private slots:
    void on_btnStart_clicked();

    void on_btnPause_clicked();

    void on_btnStop_clicked();

    void on_btnResume_clicked();

private:
    Ui::Widget *ui;
    MyThread *myT;
};
#endif // WIDGET_H

widget.cpp

最后的效果 

差不多可以了

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值