QT多线程的使用(一):moveToThread

QT有两种实现多线程的方法,方法一是“子类化QThread,然后去重写run函数,实现多线程”。方法二是“子类化QObject,然后使用moveToThread函数实现多线程”。由于QT官方推荐使用第二种方法,所以这里主要介绍一下,如何通过子类化QObject去实现多线程。

#ifndef WORK_H
#define WORK_H

#include <QObject>
#include <QThread>
class Work : public QObject
{
    Q_OBJECT
public:
    explicit Work(QObject *parent = nullptr);

signals:

public slots:
    void thread_fun();   //定义将在子线程中运行的槽函数
public:

};

#endif // WORK_H

其次,我们在work.cpp中去完善构造函数与功能函数的代码,代码如下:

#include "work.h"
#include <QDebug>

Work::Work(QObject *parent) : QObject(parent)
{
    qDebug()<<"Work构造函数ID: "<<QThread::currentThreadId();
}

void Work::thread_fun()
{
    qDebug()<<"子线程功能函数ID:"<<QThread::currentThreadId();
}

第三步,我们在mainwindow.h中添加各种头文件,然后创建一个signals信号,声明一个线程和刚刚创建的work类。

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QThread>
#include "work.h"
namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = nullptr);
    ~MainWindow();

private:
    Ui::MainWindow *ui;
    QThread *thread_test;
    Work *worker;

signals:
    void toThread();
};

#endif // MAINWINDOW_H

最后我们在mainwindow.cpp中,先实例化thread_Test线程和work类,然后连接这个信号与槽函数。并且把work这个类推向子线程,并且打开子线程。代码如下:

#include "mainwindow.h"
#include "ui_mainwindow.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    worker = new Work();
    thread_test = new QThread();

    connect(this, SIGNAL(toThread()), worker, SLOT(thread_fun() ));
    //connect(this, &MainWindow::toThread, worker, &Work::thread_fun);
    worker->moveToThread(thread_test);
    thread_test->start();       //启动线程
    emit toThread();            //发送信号
}

MainWindow::~MainWindow()
{
    delete ui;
}

通过发送信号toThread(),连接槽函数执行thread_fun()。可以看到最后的输出结果,确实不在同一个线程里面,说明多线程配置是成功的。
在这里插入图片描述

  • 1
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值