Qt 多线程(继承QThread方法)

1.新建一个MyThread类,创建好以后修改继承关系,继承于QThread;
2.直接使用QThread类中的虚函数run()(这是子线程处理函数,在这种方法中有且只有一个子线程处理函数!,注意使用时不能直接调用,要通过start()间接调用),在MyThread类中对其进行重写即可。
代码如下:
mythread.h

#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QObject>
#include <QWidget>
#include <QThread>
#include <QDebug>
class MyThread : public QThread
{
    Q_OBJECT
public:
    explicit MyThread(QObject *parent = nullptr);
protected:
    //QThread类的虚函数
    //线程处理函数
    //不能直接调用,通过start()间接调用
    virtual void run();

signals:
    void isDone();

};

#endif // MYTHREAD_H

mythread.cpp

#include "mythread.h"
//QThread-->F1-->Protected Functions-->virtual void run()
MyThread::MyThread(QObject *parent) : QThread(parent)
{

}
void MyThread::run()
{
    //很复杂的数据处理,需要耗时5s
    sleep(5);
    qDebug()<<"子线程号:"<<QThread::currentThread();
    emit isDone();//处理完后发送信号


}

mywidget.h

#ifndef MYWIDGET_H
#define MYWIDGET_H

#include <QWidget>
#include <QTimer>

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

class MyWidget : public QWidget
{
    Q_OBJECT

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

    void dealTimeout();//自定义的定时器槽函数
    void dealDone();//自定义的线程结束槽函数
    void stopThread();//自定义的线程停止槽函数

private slots:
    void on_pushButton_clicked();

private:
    Ui::MyWidget *ui;
    QTimer *myTimer;

    MyThread *thread;//子线程对象
};
#endif // MYWIDGET_H

mywidget.cpp

#include "mywidget.h"
#include "ui_mywidget.h"
#include<QThread>
#include<QDebug>
MyWidget::MyWidget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::MyWidget)
{
    ui->setupUi(this);

    qDebug()<<"主线程号:"<<QThread::currentThread();

    myTimer=new QTimer(this);

    //只要定时器启动,自动触发timeout()
    connect(myTimer,&QTimer::timeout,this,&MyWidget::dealTimeout);

    //分配空间
    thread=new MyThread(this);

    //线程处理完后,会发射isDone()信号函数,触发该信号后使用自定义的槽函数去处理
    connect(thread,&MyThread::isDone,this,&MyWidget::dealDone);
    //当按下窗口右上角x时,窗口会自动触发destroyed()信号函数
    connect(this,&MyWidget::destroyed,this,&MyWidget::stopThread);
}

void MyWidget::dealDone()
{
    qDebug()<<"it is over!";
    myTimer->stop();//关闭定时器

}
void MyWidget::stopThread()
{
    //停止线程
    thread->quit();
    //等待线程处理完手头动作
    thread->wait();


}
MyWidget::~MyWidget()
{
    delete ui;
}

void MyWidget::dealTimeout()
{
    static int i=0;
    i++;
    ui->lcdNumber->display(i);
}

void MyWidget::on_pushButton_clicked()
{
    if(myTimer->isActive()==false)
    {
        myTimer->start(100);
    }
#if 0
    //模拟非常复杂的数据处理,耗时较长
    QThread::sleep(5);//void QThread::sleep(unsigned long secs)//Forces the current thread to sleep for secs seconds.
#endif

    //启动线程,处理数据
    thread->start();


}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值