Qt 简单地启动一个线程

1、简单的线程使用,本次使用 QtConcurrent 方式实现,由于它比较简单,有时候使用它还是挺方便的。

 

2、包含头文件

1 #include <QtConcurrent/QtConcurrent>

 

3、准备好线程处理函数

void Widget::_onFunction()
{
    while (m_flag) {
        qDebug() << "_onFunction:" << QThread::currentThread();
        QThread::msleep(1000);
    }
}

 

4、启动线程

QtConcurrent::run(this, &Widget::_onFunction);

 

5、完整代码

头文件

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>

QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();

private:
    void _start();

private:
    void _onFunction();

private:
    Ui::Widget *ui;
    bool m_flag;
};
#endif // WIDGET_H
源文件
 #include "widget.h"
#include "ui_widget.h"

#include <QDebug>
#include <QThread>
#include <QtConcurrent/QtConcurrent>

Widget::Widget(QWidget *parent)
    : QWidget(parent)
    , ui(new Ui::Widget)
{
    ui->setupUi(this);
    _start();
}

Widget::~Widget()
{
    delete ui;
    m_flag = false;
}

void Widget::_start()
{
    m_flag = true;
    qDebug() << "Main Thread: "<<QThread::currentThread();

    QtConcurrent::run(this, &Widget::_onFunction);
}

void Widget::_onFunction()
{
    while (m_flag) {
        qDebug() << "_onFunction:" << QThread::currentThread();
        QThread::msleep(1000);
    }
}

 

调试结果

 

posted @ 2022-08-29 17:06  想想就很离谱  阅读(586)  评论(0编辑  收藏  举报