qt中创建多线程的使用

参考博客:https://www.cnblogs.com/Emiya-Shirou/p/11318452.html

https://www.cnblogs.com/wurenzhong/p/7908317.html

实现步骤:

以下实现的是通过点击按钮可以使达到计算定时器,并让子线程进行延时六秒,然后再发出停止命令

一、创建子线程的方式

首先必须要创建一个新的C++文件,必须继承QThread,如图:

二、然后通过开始初始化工作

(1)可以在主函数mainwindow.h中加入:  thread_one *thread;

 在构造函数中加入: thread = new thread_one(this);方式进行初始化

(2)或者是通过

 thread_one  thread = new thread_one();进行初始化

三、最终将复杂的程序就放进run();函数中进行处理

具体函数的实现如下:

在thread_one.h中:

#ifndef THREAD_ONE_H
#define THREAD_ONE_H

#include <QThread>

class thread_one : public QThread
{
     Q_OBJECT
public:
    thread_one(QObject *parent = nullptr);

protected:
    void run();//多线程执行的内容将通过重新该虚函数实现
signals:
    void over();
};

#endif // THREAD_ONE_H

在thread.cpp中:

#include "thread_one.h"

thread_one::thread_one(QObject *parent) : QThread(parent)
{

}

//创建一个函数
void thread_one::run()
{
    sleep(6);//模拟一个时长6s的复杂函数,表示延时6s之后,开始发送信号
    emit over();//复杂函数结束后发出信号
}

在mainwindow.h中:

#ifndef MAINWINDOW_H
#define MAINWINDOW_H

#include <QMainWindow>
#include <QTimer>
#include "thread_one.h"

namespace Ui {
class MainWindow;
}

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    explicit MainWindow(QWidget *parent = 0);
    ~MainWindow();
    void dealclicked();
    void dealtimeout();

private slots:
    void dealover();//处理新线程返回的结束信号

private:
    Ui::MainWindow *ui;
    QTimer *timer;
    thread_one *thread;
};

#endif // MAINWINDOW_H

在mainwindow.cpp中:

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

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::MainWindow)
{
    ui->setupUi(this);
    timer = new QTimer(this);
    thread = new thread_one(this);
    connect(ui->pushButton,&QPushButton::clicked,this,&MainWindow::dealclicked);//按下按钮后执行dealclicked()槽函数
    connect(timer,&QTimer::timeout,this,&MainWindow::dealtimeout);//根据定时器发出的信号更新LCD显示器的数字
    connect(thread,&thread_one::over,this,&MainWindow::dealover);//当开辟的线程内的复杂函数执行完后,发出over信号,接收到该信号后便停下计时器
}

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

void MainWindow::dealclicked()
{
    timer->start(100);//启动计时器,每隔0.1s的时候发送一个信号,并且是每隔0.1时间耗尽的时候,就会执行dealtimeout槽函数
    thread->start();//QThread 的对象通过start()函数调用线程文件中的run()函数
}

void MainWindow::dealtimeout()//更新LCD显示器的数字
{
    static int time = 0;
    ui->lcdNumber->display(time);
    time++;
}

void MainWindow::dealover()//接收到信号后停下计时器
{
    timer->stop();
}

点击开始之后,就开始实现效果如图所示:

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值