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

多线程实现倒计时

相关推荐
应用市场2 小时前
构建自定义命令行工具 - 打造专属指令体
开发语言·windows·python
Dfreedom.2 小时前
一文掌握Python四大核心数据结构:变量、结构体、类与枚举
开发语言·数据结构·python·变量·数据类型
一半烟火以谋生2 小时前
Python + Pytest + Allure 自动化测试报告教程
开发语言·python·pytest
虚行2 小时前
C#上位机工程师技能清单文档
开发语言·c#
小羊在睡觉3 小时前
golang定时器
开发语言·后端·golang
CoderCodingNo3 小时前
【GESP】C++四级真题 luogu-B4068 [GESP202412 四级] Recamán
开发语言·c++·算法
Larry_Yanan4 小时前
QML学习笔记(四十四)QML与C++交互:对QML对象设置objectName
开发语言·c++·笔记·qt·学习·ui·交互
百锦再4 小时前
对前后端分离与前后端不分离(通常指服务端渲染)的架构进行全方位的对比分析
java·开发语言·python·架构·eclipse·php·maven
Want5954 小时前
C/C++大雪纷飞①
c语言·开发语言·c++
有时间要学习5 小时前
Qt——窗口
开发语言·qt