Qt多线程

Qt多线程有两种方法:
1、定义一个QThread的派生类,重写run函数,run函数中的程序就是新线程中要执行的内容。在主线程中实例化该类,调用start函数,就可以实现多线程。
2、定义一个QObject的派生类,把要在新线程中执行的内容写在一个槽函数中,然后把该派生类的对象传给QThread对象的moveToThread函数,用一个信号和槽函数绑定,当信号触发时,槽函数中的内容就会在子线程执行。


第一种方法


首先定义一个QThread的派生类

#ifndef MTHREAD_H
#define MTHREAD_H
#include<QThread>
#include<QDebug>
class MThread : public QThread
{
    Q_OBJECT
public:
    MThread();
    void run() override;
};

#endif // MTHREAD_H

重写run函数,把子线程要执行的内容写到run函数中

#include "mthread.h"

MThread::MThread()
{
    qDebug()<<"子线程构造函数PID:"<<QThread::currentThreadId();
}

void MThread::run()
{
    qDebug()<<"子线程PID:"<<QThread::currentThreadId();
}

把上面定义的类加到Widget类中

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include"mthread.h"
class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
private:
    MThread * thread;
};
#endif // WIDGET_H

在主线程中实例化上面定义的类,然后调用start函数,启动子线程。

#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent),thread(new MThread)
{
    qDebug()<<"主线程PID:"<<QThread::currentThreadId();
    thread->start();
}

Widget::~Widget()
{
}

编译运行可以看到,MThread在主线程中实例化,然后run函数的内容在子线程运行。
在这里插入图片描述


第二种方法


先定义一个QObject的派生类,并定义一个threadfun函数(子线程要执行的内容就写在这个函数中)

#ifndef THREAD_H
#define THREAD_H

#include <QObject>
#include<QThread>
class Mthread : public QObject
{
    Q_OBJECT
public:
    explicit Mthread(QObject *parent = nullptr);
    void threadfun();
};

#endif // THREAD_H

实现构造函数和子线程功能函数

#include "thread.h"
#include<QDebug>
Mthread::Mthread(QObject *parent) : QObject(parent)
{
    qDebug()<<"子线程构造函数ID:"<<QThread::currentThreadId();
}

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

把刚刚定义的类添加到widget中,并定义一个信号。

#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include<QThread>
#include"thread.h"
class Widget : public QWidget
{
    Q_OBJECT

public:
    Widget(QWidget *parent = nullptr);
    ~Widget();
signals:
    void tothread();
private:
    QThread *thread_test;
    Mthread *thread_class;
    QThread *thread_another;
};
#endif // WIDGET_H

先实例化我们定义的Mthread类,然后定义一个Qt自带的QThread类,把信号和子线程功能函数connect在一起。然后把实例化的Mthread作为参数传给QThread的moveToThread函数,再调用start函数。当触发信号后,子线程功能函数就会在子线程执行。

#include "widget.h"

Widget::Widget(QWidget *parent)
    : QWidget(parent)
{
    thread_test=new QThread();
    thread_class=new Mthread();
    thread_another=new QThread();
    connect(this,&Widget::tothread,thread_class,&Mthread::threadfun);
    thread_class->moveToThread(thread_test);
    thread_test->start();
    emit tothread();
}

Widget::~Widget()
{
}


在这里插入图片描述
多说一嘴,Qt对控件的刷新操作只能是在主线程中,在子线程操作控件时,程序会直接死掉。

  • 7
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值