• QT使用QThread创建线程的方法


     

    QT使用QThread启动线程的方法 

     创建项目文件基类选择QDialog,添加两个按钮

    分别按钮右键-》转到槽,添加代码

    点击启动线程,

    thread2.start();默认调用my_thread类的run函数
    
    1. #include "dialog.h"
    2. #include "ui_dialog.h"
    3. #include
    4. Dialog::Dialog(QWidget *parent)
    5. : QDialog(parent)
    6. , ui(new Ui::Dialog)
    7. {
    8. ui->setupUi(this);
    9. }
    10. Dialog::~Dialog()
    11. {
    12. delete ui;
    13. }
    14. void Dialog::on_pushButton_start_clicked()
    15. {
    16. thread2.start();
    17. ui->pushButton_start->setEnabled(false);
    18. ui->pushButton_stop->setEnabled(true);
    19. }
    20. void Dialog::on_pushButton_stop_clicked()
    21. {
    22. if(thread2.isRunning())
    23. {
    24. thread2.stop();
    25. ui->pushButton_start->setEnabled(true);
    26. ui->pushButton_stop->setEnabled(false);
    27. }
    28. else
    29. {
    30. qDebug()<<tr("线程已经停止");
    31. }
    32. }

    dialog.h

    1. #ifndef DIALOG_H
    2. #define DIALOG_H
    3. #include
    4. #include "my_thread.h"
    5. QT_BEGIN_NAMESPACE
    6. namespace Ui { class Dialog; }
    7. QT_END_NAMESPACE
    8. class Dialog : public QDialog
    9. {
    10. Q_OBJECT
    11. public:
    12. Dialog(QWidget *parent = nullptr);
    13. ~Dialog();
    14. private slots:
    15. void on_pushButton_start_clicked();
    16. void on_pushButton_stop_clicked();
    17. private:
    18. Ui::Dialog *ui;
    19. my_thread thread2;
    20. };
    21. #endif // DIALOG_H

     

    #include 

    创建my_thread的类

    头文件:

    1. #ifndef MY_THREAD_H
    2. #define MY_THREAD_H
    3. #include
    4. class my_thread : public QThread
    5. {
    6. Q_OBJECT
    7. public:
    8. explicit my_thread(QObject *parent = 0);
    9. void stop();
    10. protected:
    11. void run();
    12. private:
    13. volatile bool stopped;//volatile可以使stopped变量任何时候都保持最新的值
    14. };
    15. #endif // MY_THREAD_H

    cpp文件

     

    1. #include "my_thread.h"
    2. #include
    3. my_thread::my_thread(QObject * parent):QThread(parent)
    4. {
    5. stopped=false;
    6. }
    7. void my_thread::run()
    8. {
    9. qreal i=0;// QT的浮点型
    10. while(!stopped)
    11. {
    12. qDebug()<<QString("in my_thread:%1").arg(i);
    13. msleep(1000);
    14. i++;
    15. }
    16. stopped = false;
    17. qDebug()<<tr("线程已经停止啦");
    18. }
    19. void my_thread::stop()
    20. {
    21. stopped=true;
    22. }

  • 相关阅读:
    7、Instant-ngp
    【设计模式】工厂模式
    网络与TCP-IP
    C++进阶篇5-哈希
    flutter进度条动画
    java基于springboot的学生素质考评管理系统的设计与实现
    Python多进程开发
    汇编语言与微机原理 期末复习题整理(大题)
    RabbitMQ消息的可靠性
    双软认证需要什么条件
  • 原文地址:https://blog.csdn.net/txwtech/article/details/126376107