【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.演示

多线程实现倒计时

相关推荐
爱掉发的小李39 分钟前
前端开发中的输出问题
开发语言·前端·javascript
zyx没烦恼1 小时前
五种IO模型
开发语言·c++
Q_Q5110082851 小时前
python的婚纱影楼管理系统
开发语言·spring boot·python·django·flask·node.js·php
EutoCool1 小时前
Qt窗口:菜单栏
开发语言·c++·嵌入式硬件·qt·前端框架
nightunderblackcat2 小时前
新手向:使用Python将多种图像格式统一转换为JPG
开发语言·python
我爱Jack2 小时前
深入解析 LinkedList
java·开发语言
engchina2 小时前
Python PDF处理库深度对比:PyMuPDF、pypdfium2、pdfplumber、pdfminer的关系与区别
开发语言·python·pdf
拓端研究室2 小时前
专题:2025供应链数智化与效率提升报告|附100+份报告PDF、原数据表汇总下载
开发语言·php
一百天成为python专家3 小时前
python库之jieba 库
开发语言·人工智能·python·深度学习·机器学习·pycharm·python3.11
Go Dgg3 小时前
【Go + Gin 实现「双 Token」管理员登录】
开发语言·golang·gin