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

多线程实现倒计时

相关推荐
froginwe1117 分钟前
《WebPages 邮局》
开发语言
@insist12327 分钟前
网络工程师-广域网与接入网技术(一):核心协议与流量控制
开发语言·网络·网络工程师·软考·软件水平考试
森G39 分钟前
40、对话框---------事件系统
c++·qt
ˇasushiro44 分钟前
终端工具配置
开发语言·ios·swift
不写八个1 小时前
PHP教程005:配置ThinkPHP环境
开发语言·php
迷海1 小时前
C++内存对齐
开发语言·c++
炘爚1 小时前
C++(流类:istream /ostream/istringstream /ostringstream)
开发语言·c++·算法
Gse0a362g1 小时前
推荐 PHP 属性(Attributes) 简洁读取 API 扩展包
android·开发语言·php
塞北山巅1 小时前
Windows 下基于 MSYS2 搭建 C++ 开发环境:从安装到配置全指南
开发语言·c++·windows