QT开发中文网

QT c++用 qlabel显示写一个时间倒计时

在 Qt 中使用 QLabel 显示时间倒计时,可以使用 QTimer 来定期更新 QLabel 的文本。下面是一个简单的示例,演示如何实现一个 10 秒的倒计时。

#include <QApplication>
#include <QWidget>
#include <QLabel>
#include <QVBoxLayout>
#include <QTimer>

class CountdownTimer : public QWidget {
    Q_OBJECT

public:
    CountdownTimer(QWidget *parent = nullptr) : QWidget(parent), remainingTime(10) {
        // 创建 QLabel 用于显示倒计时
        label = new QLabel(this);
        updateLabel();

        // 创建布局并添加 QLabel
        QVBoxLayout *layout = new QVBoxLayout(this);
        layout->addWidget(label);

        // 创建定时器,每秒触发一次
        timer = new QTimer(this);
        connect(timer, &QTimer::timeout, this, &CountdownTimer::updateCountdown);
        timer->start(1000); // 每1000毫秒(1秒)触发一次
    }

private slots:
    void updateCountdown() {
        if (remainingTime > 0) {
            remainingTime--;
            updateLabel();
        } else {
            timer->stop(); // 倒计时结束,停止定时器
            label->setText("时间到!");
        }
    }

private:
    void updateLabel() {
        label->setText(QString("剩余时间: %1 秒").arg(remainingTime));
    }

    QLabel *label;
    QTimer *timer;
    int remainingTime; // 剩余时间(以秒为单位)
};

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

    CountdownTimer countdown;
    countdown.setWindowTitle("倒计时器");
    countdown.resize(300, 200);
    countdown.show();

    return app.exec();
}

#include "main.moc"

说明:

  1. 包含头文件:包括 Qt 应用程序和窗口部件所需的头文件。
  2. CountdownTimer 类:这是一个继承自 QWidget 的类,用于创建倒计时器界面。
  3. 构造函数:在构造函数中,我们创建了 QLabelQTimer,并设置定时器每秒触发一次。
  4. updateCountdown 槽函数:这个槽会在每次定时器超时时被调用,如果剩余时间大于零,则减少剩余时间并更新标签,否则停止定时器并显示“时间到!”。
  5. 主函数:创建 QApplication 对象,并实例化我们的 CountdownTimer 类。

编译与运行:

要编译此代码,请确保已安装 Qt 开发环境,然后将其放入合适的项目文件夹中,使用 qmake 和 make 构建。


内容由零声教学AI助手提供,问题来源于学员提问

目录导航
  • 说明:
  • 编译与运行:
  • 本站部分文章来源于网络,版权归原作者所有,如有侵权请联系站长删除。
    转载请注明出处:https://qt.0voice.com/?id=12737

    分享:
    扫描分享到社交APP
    上一篇
    下一篇
    发表列表
    游客 游客
    此处应有掌声~
    评论列表

    还没有评论,快来说点什么吧~

    联系我们

    在线咨询: 点击这里给我发消息

    微信号:3007537140

    上班时间: 10:30-22:30

    关注我们
    x

    注册

    已经有帐号?