【Qt】创建线程程序示例
生活随笔
收集整理的這篇文章主要介紹了
【Qt】创建线程程序示例
小編覺得挺不錯的,現在分享給大家,幫大家做個參考.
00. 目錄
文章目錄
- 00. 目錄
- 01. 概述
- 02. 開發環境
- 03. 創建線程類子類
- 04. 主窗口和程序
- 05. 程序執行結果
- 06. 附錄
01. 概述
多線程編程可以有效解決在不凍結一個應用程序用戶界面的情況下執行一個耗時操作的問題。線程相關內容可以在幫助中通過"Thread Support in Qt"關鍵字查看。
02. 開發環境
Windows系統:Windows10
Qt版本:Qt5.15或者Qt6
03. 創建線程類子類
mythread.h文件
#ifndef MYTHREAD_H #define MYTHREAD_H#include <QThread> #include <QObject>class MyThread : public QThread {Q_OBJECT public:MyThread(QObject *parent = 0);~MyThread();void stop();protected:void run();private:volatile bool stopped; };#endif // MYTHREAD_Hmythread.cpp文件
#include "mythread.h"#include <QDebug>MyThread::MyThread(QObject *parent):QThread(parent) {stopped = false; }MyThread::~MyThread() {}void MyThread::stop() {stopped = true; }void MyThread::run() {qreal i = 0;while(!stopped){qDebug() << QString("子線程: %1").arg(i);msleep(1000);i++;}stopped = false; }04. 主窗口和程序
主界面設計
dialog.h
#ifndef DIALOG_H #define DIALOG_H#include <QDialog>#include "mythread.h"QT_BEGIN_NAMESPACE namespace Ui { class Dialog; } QT_END_NAMESPACEclass Dialog : public QDialog {Q_OBJECTpublic:Dialog(QWidget *parent = nullptr);~Dialog();private slots://啟動線程void on_pushButton_clicked();//終止線程void on_pushButton_2_clicked();private:Ui::Dialog *ui;MyThread thread; }; #endif // DIALOG_Hdialog.cpp
#include "dialog.h" #include "ui_dialog.h"Dialog::Dialog(QWidget *parent): QDialog(parent), ui(new Ui::Dialog) {ui->setupUi(this); }Dialog::~Dialog() {delete ui; }//啟動線程 void Dialog::on_pushButton_clicked() {thread.start();ui->pushButton->setEnabled(false);ui->pushButton_2->setEnabled(true);}//終止線程 void Dialog::on_pushButton_2_clicked() {if (thread.isRunning()){thread.stop();ui->pushButton->setEnabled(true);ui->pushButton_2->setEnabled(false);} }05. 程序執行結果
"子線程: 0" "子線程: 1" "子線程: 2" "子線程: 3" "子線程: 4" "子線程: 5"06. 附錄
6.1 Qt教程匯總
網址:https://dengjin.blog.csdn.net/article/details/115174639
6.2 程序下載
下載:2Thread.rar
總結
以上是生活随笔為你收集整理的【Qt】创建线程程序示例的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 【工业控制】PolyWorks培训教程-
- 下一篇: 【Qt】 Qt中实时更新UI程序示例