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;
}