本例子实现生成两个线程,向屏幕输出消息。
Qt创建ThreadDialog,编辑threaddialog.h和threaddialog.cpp
threaddialog.h代码实现:
#ifndef THREADDIALOG_H #define THREADDIALOG_H #include <QDialog> #include <QtWidgets> #include "thread.h" //导入自定义类 namespace Ui { class ThreadDialog; } class ThreadDialog : public QDialog { Q_OBJECT public: explicit ThreadDialog(QWidget *parent = 0); ~ThreadDialog(); protected: void closeEvent(QCloseEvent *);//设置关闭事件 private: Ui::ThreadDialog *ui; //定义两个线程,其中Thread是自定义类 Thread threadA; Thread threadB; private slots: //三个按钮对应的消息槽 void starOrStopThreadA(); void starOrStopThreadB(); //void quitSlot(); }; #endif // THREADDIALOG_H
threaddialog.cpp代码实现:
#include "threaddialog.h" #include "ui_threaddialog.h" ThreadDialog::ThreadDialog(QWidget *parent) : QDialog(parent), ui(new Ui::ThreadDialog) { ui->setupUi(this); QObject::connect(ui->threadAButton,SIGNAL(clicked(bool)),this,SLOT(starOrStopThreadA())); QObject::connect(ui->threadBButton,SIGNAL(clicked(bool)),this,SLOT(starOrStopThreadB())); //QObject::connect(ui->quitButton,SIGNAL(clicked(bool)),this,SLOT(close())); threadA.setMessage("A"); threadB.setMessage("B"); } ThreadDialog::~ThreadDialog() { delete ui; } void ThreadDialog::closeEvent(QCloseEvent *event) { threadA.stop(); threadB.stop(); threadA.wait(); threadB.wait(); event->accept(); } void ThreadDialog::starOrStopThreadA() { if(threadA.isRunning()) //当再次点击ButtonA时,启动stop() { threadA.stop(); ui->threadAButton->setText("start A"); } else//当点击开始ButtonA时,如果A没有运行,则启动A线程 { threadA.start(); ui->threadAButton->setText("stop A"); } } void ThreadDialog::starOrStopThreadB() { if(threadB.isRunning()) { threadB.stop(); ui->threadBButton->setText("start B"); } else { threadB.start(); ui->threadBButton->setText("stop B"); } }
自定义类thread.h代码实现:
#ifndef THREAD_H #define THREAD_H #include <QThread> #include <QtDebug> class Thread : public QThread { public: Thread(); void setMessage(const QString &message); void stop(); //已从QThread中继承得到start()方法 protected: void run(); private: QString messageStr;//输出的信息 volatile bool stopped;//控制线程的开关 }; #endif // THREAD_H
thread.cpp代码实现:
#include "thread.h" #include <iostream> using namespace std; Thread::Thread() { stopped = false;//初始线程是开始的 } void Thread::setMessage(const QString &message) { messageStr = message; } void Thread::run() //启动A线程之后,先屏幕不断得输出消息,知道stopped变成true { while(!stopped) { cerr <<messageStr.toStdString();//将设置的字符串信息设置输出到debug sleep(1); } stopped = false; //将stopped设置false,便于另一个线程继续执行 } void Thread::stop() //将stopped设置true,即停止线程 { stopped = true; }
Ui如图所示: