qt-C++笔记之带有倒计数显示的按钮,计时期间按钮锁定

qt-C++笔记之带有倒计数显示的按钮,计时期间按钮锁定

code review!

文章目录

1.运行

2.main.cc

代码

cpp 复制代码
#include <QApplication>
#include <QPushButton>
#include <QTimer>
#include <QFont>

int main(int argc, char *argv[])
{
    QApplication app(argc, argv);

    // 创建主窗口
    QWidget window;
    window.setWindowTitle("倒计时按钮示例");

    // 创建按钮
    QPushButton button(&window);
    button.setText("开始倒计时");
    button.setGeometry(50, 50, 150, 50);

    // 创建计时器
    QTimer timer;
    timer.setInterval(1000); // 设置计时器间隔为1秒(1000毫秒)

    int countDown = 2; // 倒计时初始值

    // 设置按钮的样式
    button.setStyleSheet("font-size: 20px; font-weight: bold;");

    // 定义按钮点击事件的处理函数
    QObject::connect(&button, &QPushButton::clicked, [&button, &timer, &countDown]() {
        button.setEnabled(false); // 禁用按钮
        timer.start(); // 启动计时器
        button.setText(QString::number(countDown)); // 显示倒计时初始值
    });

    // 定义计时器超时事件的处理函数
    QObject::connect(&timer, &QTimer::timeout, [&button, &timer, &countDown]() {
        countDown--; // 倒计时减1
        if (countDown > 0) {
            button.setText(QString::number(countDown)); // 更新按钮上的倒计时数字
        } else {
            button.setEnabled(true); // 启用按钮
            button.setText("开始倒计时");
            timer.stop(); // 停止计时器
            countDown = 2; // 重置倒计时初始值
        }
    });

    // 运行应用程序
    window.show();
    return app.exec();
}

3.main.pro

代码

bash 复制代码
QT += widgets

TARGET = FileContentReader
TEMPLATE = app

SOURCES += main.cpp

HEADERS +=

FORMS +=

DISTFILES += \
相关推荐
ReedFoley10 分钟前
【笔记】动手学Ollama 第五章 Ollama 在 LangChain 中的使用 - Python 集成
笔记·langchain
zylyehuo15 分钟前
C++基础编程
c++
tt5555555555551 小时前
C/C++嵌入式笔试核心考点精解
c语言·开发语言·c++
lg_cool_1 小时前
Qt 中最经典、最常用的多线程通信场景
c++·qt6.3
科大饭桶2 小时前
C++入门自学Day14-- Stack和Queue的自实现(适配器)
c语言·开发语言·数据结构·c++·容器
tt5555555555552 小时前
字符串与算法题详解:最长回文子串、IP 地址转换、字符串排序、蛇形矩阵与字符串加密
c++·算法·矩阵
rainFFrain3 小时前
Boost搜索引擎项目(详细思路版)
网络·c++·http·搜索引擎
long_run4 小时前
C++之模板函数
c++
NuyoahC4 小时前
笔试——Day43
c++·算法·笔试
feiyangqingyun4 小时前
纯Qt结合ffmpeg实现本地摄像头采集/桌面采集/应用程序窗口采集/指定采集帧率和分辨率等
qt·ffmpeg·qt桌面采集·qt摄像头采集·qt程序窗口采集