111200
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
#include "subthread.h"
#include <QThread>
namespace Ui {
class MainWindow;
}
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
explicit MainWindow(QWidget *parent = 0);
~MainWindow();
private slots:
void on_btn_clicked();
void receiveData(int cd);
private:
Ui::MainWindow *ui;
QThread *thread;
};
#endif // MAINWINDOW_H
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include "subthread.h"
MainWindow::MainWindow(QWidget *parent) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
thread=new QThread();
subthread *st=new subthread();
st->moveToThread(thread);
connect(thread,QThread::finished,st,subthread::deleteLater);
connect(thread,QThread::started,st,subthread::Run);
connect(st,subthread::sendData,this,MainWindow::receiveData);
}
MainWindow::~MainWindow()
{
delete ui;
thread->deleteLater();
}
void MainWindow::on_btn_clicked()
{
thread->start();
ui->btn->setDisabled(true);
}
void MainWindow::receiveData(int cd)
{
ui->textEdit1->append(QString::number(cd));
}
#ifndef SUBTHREAD_H
#define SUBTHREAD_H
#include <QObject>
class subthread : public QObject
{
Q_OBJECT
public:
explicit subthread(QObject *parent = nullptr);
signals:
void sendData(int cnt);
public slots:
void Run();
};
#endif // SUBTHREAD_H
#include "subthread.h"
#include <QThread>
subthread::subthread(QObject *parent) : QObject(parent)
{
}
void subthread::Run()
{
int cnt=10;
while(cnt>0)
{
emit sendData(cnt--);
QThread::msleep(100);
}
QThread::currentThread()->quit();
}
标签:include,thread,void,案例,ui,subthread,多线程,MainWindow From: https://www.cnblogs.com/dq0618/p/17830559.html