MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "MyThread.h"
#include <QThread>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private:
Ui::MainWindow *ui;
private:
MyThread *myObject;
QThread *newThread;
private slots:
void SlotNum(QString num);
};
#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);
newThread = new QThread;
myObject = new MyThread;
myObject->moveToThread(newThread); //创建线程
connect(newThread, &QThread::started ,myObject, &MyThread::display);
connect(myObject, &MyThread::SiganlNum, this, &MainWindow::SlotNum);
connect(ui->pushButton_open, &QPushButton::clicked, this, [=]
{
newThread->start();
myObject->filenameList(10);
myObject->stopwork(false);//开始
});
connect(ui->pushButton_over, &QPushButton::clicked, this, [=]
{
myObject->stopwork(true);//停止
newThread->quit();
newThread->wait(); //等待线程退出
});
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::SlotNum(QString num)
{
ui->lcdNumber->display(num);
}
MyThread.h
#ifndef MYTHREAD_H
#define MYTHREAD_H
#include <QObject>
#include <QFileInfo>
class MyThread : public QObject
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = nullptr);
public slots:
void display();
void stopwork(bool stop);
public:
void filenameList(const int &ss);
signals:
void SiganlNum(QString num);
private:
bool m_stop_;
int num;
};
#endif // MYTHREAD_H
MyThread.cpp
#include "MyThread.h"
#include <QDebug>
#include <QThread>
MyThread::MyThread(QObject *parent) : QObject(parent)
{
m_stop_ = false;
num = 0;
}
void MyThread::display()
{
int i = 0;
while(1)
{
if(m_stop_)
{
break;
}
qDebug() << "i is" << num;
num++;
emit SiganlNum(QString::number(num));
QThread::sleep(1);
}
}
void MyThread::stopwork(bool stop)
{
m_stop_ = stop;
}
void MyThread::filenameList(const int &ss)
{
num = ss;
}