【QT学习之路】QThread的简单使用

QThread的使用说明:QThread线程类是QT已经封装好的, 如果要使用线程, 就派生出子类并且实现线程接口函数run(run就是线程任务函数)

下面就用QThread实现当前系统时间的获取并且在主界面(UI线程)上显示,实现方法:在子线程中采集系统时间,通过信号发送给UI线程, 在ui线程上显示。

一、在QT工程中,新建一个类,并继承QThread

二、子线程类实现采集系统时间

头文件(timethread.h)代码

1、为了让我们的子类与QT已有的QThread类很相似,我们派生类的构造函数改成与父类的构造函数一样

2、发送时间是通过信号发送给UI线程,需要加Q_OBJECT,这样才能使用信号与槽函数

具体代码

#ifndef TIMETHREAD_H
#define TIMETHREAD_H

#include <QObject>
#include <QThread>

class TimeThread : public QThread
{
    Q_OBJECT //使用信号与槽函数
public:
    explicit TimeThread(QObject *parent = nullptr);
    //实现run接口
    void run();
//声明信号
signals:
    void sendTime(QString );
};

#endif // TIMETHREAD_H

cpp文件(timethread.cpp)代码

  通过接口函数run,实现每隔1秒获取当前系统时间,并用emit将信号发送出去

#include "timethread.h"
#include <QTime>
#include <QDebug>
TimeThread::TimeThread(QObject *parent):QThread(parent)
{

}
void TimeThread::run()
{
    //线程任务
    while(1)
    {
        qDebug()<<currentThreadId();
        QString t = QTime::currentTime().toString("hh:mm:ss");
        //延时
        sleep(1);
        //通过信号把时间发送出去
        emit sendTime(t);
    }
}

三、UI界面设计

四、UI线程的具体实现

1、关联字线程发送的信号(sendTime)

2、通过两个按钮实现启动和停止线程

3、将接收到的时间显示在液晶显示屏上

具体代码

#include "threadshowtime.h"
#include "ui_threadshowtime.h"

ThreadShowTime::ThreadShowTime(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::ThreadShowTime)
{
    ui->setupUi(this);
    //关联线程的sendTime信号
    connect(&th, &TimeThread::sendTime, this, &ThreadShowTime::show_time);
}

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

void ThreadShowTime::on_startBt_clicked()
{
    //启动线程
    th.start();
}

void ThreadShowTime::on_stopBt_clicked()
{
    //线程停止
    th.terminate();
}

void ThreadShowTime::show_time(QString t)
{
    ui->lcdNumber->display(t);
}

五、效果展示

问题咨询及项目源码请加群:

QQ群

名称:IT项目交流群

群号:245022761

  • 11
    点赞
  • 72
    收藏
    觉得还不错? 一键收藏
  • 9
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值