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

多线程实现倒计时

相关推荐
Felix_One1 天前
Qt 串口通信避坑指南:QSerialPort 的 5 个常见问题
qt
blasit4 天前
笔记:Qt C++建立子线程做一个socket TCP常连接通信
c++·qt·tcp/ip
郑州光合科技余经理9 天前
代码展示:PHP搭建海外版外卖系统源码解析
java·开发语言·前端·后端·系统架构·uni-app·php
feifeigo1239 天前
matlab画图工具
开发语言·matlab
dustcell.9 天前
haproxy七层代理
java·开发语言·前端
norlan_jame9 天前
C-PHY与D-PHY差异
c语言·开发语言
多恩Stone9 天前
【C++入门扫盲1】C++ 与 Python:类型、编译器/解释器与 CPU 的关系
开发语言·c++·人工智能·python·算法·3d·aigc
QQ4022054969 天前
Python+django+vue3预制菜半成品配菜平台
开发语言·python·django
遥遥江上月9 天前
Node.js + Stagehand + Python 部署
开发语言·python·node.js
m0_531237179 天前
C语言-数组练习进阶
c语言·开发语言·算法