【qt】多线程实现倒计时

1.界面设计

设置右边的intvalue从10开始倒计时

2.新建Thread类

新建Thread类,使其继承QThread类,多态重写run函数,相当于线程执行函数

3.重写run函数

重写run函数,让另一个进程每隔1s发出一个信号,主线程使用connect捕捉

4.创建一个线程

5.connect函数连接信号和处理函数

6.实现处理函数

7.源码

thread.h

c 复制代码
#ifndef THREAD_H
#define THREAD_H

#include <QObject>
#include<QThread>
class Thread : public QThread
{
    Q_OBJECT
public:
    Thread();
    virtual void run() override;
signals:
    void notify();
};

#endif // THREAD_H

widget.h

c 复制代码
#ifndef WIDGET_H
#define WIDGET_H

#include <QWidget>
#include"thread.h"
QT_BEGIN_NAMESPACE
namespace Ui { class Widget; }
QT_END_NAMESPACE

class Widget : public QWidget
{
    Q_OBJECT

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

private:
    Ui::Widget *ui;
    Thread thread;
};
#endif // WIDGET_H

thread.cpp

c 复制代码
#include "thread.h"

Thread::Thread()
{

}


void Thread::run()
{

    for(int i=0;i<10;i++)
    {
       sleep(1);
       emit notify();



    }

}

widget.cpp

c 复制代码
#include "widget.h"
#include "ui_widget.h"

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

    thread.start();

    connect(&thread,&Thread::notify,this,&Widget::deal);
}
 void Widget::deal()
 {
    int value=ui->lcdNumber->intValue();
     value--;
     ui->lcdNumber->display(value);

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

8.演示

多线程实现倒计时

相关推荐
小陈不好吃几秒前
Java 泛型与类型擦除:从 PECS 原则到 TypeToken 绕过
java·开发语言·windows·pecs 原则·typetoken绕过
Shaoshing14 分钟前
存储引擎与架构
java·开发语言·架构
额额额对了31 分钟前
Linux 驱动开发:基于 platform 总线 + misc 设备的 DS18B20 单总线温度驱动
linux·c语言·开发语言·驱动开发·嵌入式硬件
devilnumber37 分钟前
Java 代理模式(简单理解回顾)
java·开发语言·代理模式
invicinble1 小时前
对服务器资源的理解--理解用户请求,部署,服务器资源相关的映射层
开发语言
漫步人生走在路上1 小时前
用小语种SEO突破外贸B2B天花板:法语、德语市场的实测数据
开发语言·前端·javascript·人工智能·搜索引擎·ecmascript
yuniko-n1 小时前
【JUC】线程池
java·开发语言
dwm888888881 小时前
c# 创建使用本地NuGet包
开发语言·c#
2601_962885721 小时前
如何用 Python 获取上证指数、沪深300、中证500 等指数行情?
开发语言·python
张张123y2 小时前
后端第六课:Python 语法速通(0 基础入门,AI 应用开发的第一门语言)
开发语言·人工智能·python·ai·后端开发