创建项目文件基类选择QDialog,添加两个按钮
分别按钮右键-》转到槽,添加代码
点击启动线程,
thread2.start();默认调用my_thread类的run函数
- #include "dialog.h"
- #include "ui_dialog.h"
- #include
-
-
- Dialog::Dialog(QWidget *parent)
- : QDialog(parent)
- , ui(new Ui::Dialog)
- {
- ui->setupUi(this);
- }
-
- Dialog::~Dialog()
- {
- delete ui;
- }
-
-
- void Dialog::on_pushButton_start_clicked()
- {
- thread2.start();
- ui->pushButton_start->setEnabled(false);
- ui->pushButton_stop->setEnabled(true);
- }
-
- void Dialog::on_pushButton_stop_clicked()
- {
- if(thread2.isRunning())
- {
- thread2.stop();
- ui->pushButton_start->setEnabled(true);
- ui->pushButton_stop->setEnabled(false);
- }
- else
- {
- qDebug()<<tr("线程已经停止");
- }
- }
dialog.h
- #ifndef DIALOG_H
- #define DIALOG_H
-
- #include
- #include "my_thread.h"
-
- QT_BEGIN_NAMESPACE
- namespace Ui { class Dialog; }
- QT_END_NAMESPACE
-
- class Dialog : public QDialog
- {
- Q_OBJECT
-
- public:
- Dialog(QWidget *parent = nullptr);
- ~Dialog();
-
- private slots:
- void on_pushButton_start_clicked();
-
- void on_pushButton_stop_clicked();
-
- private:
- Ui::Dialog *ui;
- my_thread thread2;
- };
- #endif // DIALOG_H
#include
创建my_thread的类
头文件:
- #ifndef MY_THREAD_H
- #define MY_THREAD_H
- #include
-
-
- class my_thread : public QThread
- {
- Q_OBJECT
- public:
- explicit my_thread(QObject *parent = 0);
- void stop();
- protected:
- void run();
- private:
- volatile bool stopped;//volatile可以使stopped变量任何时候都保持最新的值
- };
-
- #endif // MY_THREAD_H
cpp文件
- #include "my_thread.h"
- #include
-
- my_thread::my_thread(QObject * parent):QThread(parent)
- {
- stopped=false;
- }
- void my_thread::run()
- {
- qreal i=0;// QT的浮点型
- while(!stopped)
- {
- qDebug()<<QString("in my_thread:%1").arg(i);
- msleep(1000);
- i++;
- }
- stopped = false;
- qDebug()<<tr("线程已经停止啦");
- }
- void my_thread::stop()
- {
- stopped=true;
- }