QT中提供的QThread是平台无关的。一般但线程操作也就四个方面内容
- 线程的创建
- 线程的启动、停止、 挂起
thread.start();run();
thread.stop();
thread.wait();
3.进程中的事件,每个线程中的事件的目的是接收其它线程的信号。
启动、停止 exec() quit() terminate()
4.取得线程ID 或者句柄 currentThreadId() currentThread()
点击开始按钮,开始创建和运行线程,点击停止,终止线程。
代码:
MainWindow.h
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui { class MainWindow; }
QT_END_NAMESPACE
#include <QThread>
class MyThread : public QThread
{
Q_OBJECT
public:
explicit MyThread(QObject *parent = 0);
void stop();
protected:
void run();
private:
volatile bool stopped;
};
class MainWindow : public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
private slots:
void on_startButton_clicked();
void on_stopButton_clicked();
private:
Ui::MainWindow *ui;
MyThread thread;
};
#endif // MAINWINDOW_H
MainWindow.cpp
#include "mainwindow.h"
#include "ui_mainwindow.h"
#include <QDebug>
MyThread::MyThread(QObject *parent) :
QThread(parent)
{
stopped = false;
}
void MyThread::run()
{
qreal i = 0;
while (!stopped) {
qDebug() << QString("in MyThread: %1").arg(i);
msleep(1000);
i++;
}
stopped = false;
}
void MyThread::stop()
{
stopped = true;
}
MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
// 启动线程按钮
void MainWindow::on_startButton_clicked()
{
thread.start();
ui->startButton->setEnabled(false);
ui->stopButton->setEnabled(true);
}
// 终止线程按钮
void MainWindow::on_stopButton_clicked()
{
if (thread.isRunning()) {
thread.stop();
ui->startButton->setEnabled(true);
ui->stopButton->setEnabled(false);
}
}