QThread(重写run函数)

 

MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include "Mythread.h"

QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE

class MainWindow : public QMainWindow
{
    Q_OBJECT

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

private slots:
    void SlotNum(QString num);
private:
    Ui::MainWindow *ui;
    Mythread *my_thread_;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
    , ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    my_thread_ = new Mythread(this);
    connect(my_thread_, &Mythread::SigNum, this, &MainWindow::SlotNum);
    connect(ui->pushButton_open, &QPushButton::clicked, this, [=]
    {
        my_thread_->stopwork(false);//开始
        my_thread_->start();
    });
    connect(ui->pushButton_over, &QPushButton::clicked, this, [=]
    {
        my_thread_->stopwork(true);//结束
        my_thread_->quit();
        my_thread_->wait();
    });
}

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

void MainWindow::SlotNum(QString num)
{
    ui->lineEdit->setText(num);
}
Mythread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H

#include <QThread>
#include <QObject>

class Mythread : public QThread
{
    Q_OBJECT

public:
    Mythread(QObject *parent = nullptr);

signals:
    void SigNum(QString res);

private:
    void run();

public slots:
    void stopwork(bool stop);

private:
    bool m_stop_;
};

#endif // MYTHREAD_H
Mythread.cpp
#include "Mythread.h"
#include <QDebug>
Mythread::Mythread(QObject *parent):
    QThread(parent)
{
    m_stop_ = false;
}

void Mythread::run()
{
    int i = 0;
    while(1)
    {
        if(m_stop_)
        {
            break;
        }
        qDebug() << "i is" << i;
        i++;
        emit SigNum(QString::number(i));
        sleep(1);
    }
}

void Mythread::stopwork(bool stop)
{
    m_stop_ = stop;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值