【Qt】demo示例--通过定时器实现时间刷新

【Qt】demo示例--通过定时器实现时间刷新

1.背景

Qt Creator版本:4.2.0 ,如下图:

即安装qt-opensource-windows-x86-msvc2013_64-5.7.1.exe 后自带得Qt编程IDE;

2.代码

项目结构如下:

mydialog.h 头文件内容:

cpp 复制代码
//mydialog.h
#ifndef MYDIALOG_H
#define MYDIALOG_H
#include <QDialog>
#include <QTimer>
#include <QLCDNumber>
#include <QTime>
#include <QVBoxLayout>

class MyDialog : public QDialog
{
  Q_OBJECT

public:
  explicit MyDialog(QWidget *parent = 0);

signals:
public slots:
  void onTimerOut();
  
private:
  QLCDNumber *lcd;
  QTimer *timer;
};

#endif // MYDIALOG_H

mydialog.cpp 文本内容:

cpp 复制代码
// mydialog.cpp
#include "mydialog.h"

MyDialog::MyDialog(QWidget *parent):
  QDialog(parent)
{
  //新建一个QLCDNumber对象
  lcd = new QLCDNumber();

  //设置晶体管控件QLCDNumber能显示的位数
  lcd->setDigitCount(10);

  //设置显示的模式为十进制
  lcd->setMode(QLCDNumber::Dec);

  //设置显示方式
  lcd->setSegmentStyle(QLCDNumber::Flat);

  //新建一个QTimer对象,对应#include <QTimer>
  timer = new QTimer();

  //设置定时器每个多少毫秒发送一个timeout()信号
  timer->setInterval(1000);

  //启动定时器
  timer->start();

  // 对应包含 #include <QVBoxLayout>
  QVBoxLayout *layout = new QVBoxLayout();
  layout->addWidget(lcd);

  //信号和槽
  connect(timer, SIGNAL(timeout()), this, SLOT(onTimerOut()));

  //重新设置窗口的布局管理器
  this->setLayout(layout);

  //重新设置窗口的大小
  this->resize(400, 100);

  //重新设置窗口的标题
  this->setWindowTitle(QString::fromLocal8Bit("系统当前时间"));
}

void MyDialog::onTimerOut()
{
  // 获取系统当前时间,对应包含#include <QTime>
  QTime time = QTime::currentTime();

  //设置晶体管控件QLCDNumber上显示的内容
  lcd->display(time.toString("hh:mm:ss"));
}

main.cpp 文本内容:

cpp 复制代码
// main.cpp
// 基于QTimer的定时器demo
#include <QApplication>
#include "mydialog.h"
int main(int argc, char *argv[])
{
  QApplication a(argc, argv);
  MyDialog define_dialog;
  define_dialog.show();
  return a.exec();
}

3.运行

运行如下:

相关推荐
优秀的颜9 分钟前
计算机基础知识(第五篇)
java·开发语言·分布式
CodeWithMe11 分钟前
【C/C++】std::vector成员函数清单
开发语言·c++
uyeonashi11 分钟前
【QT控件】输入类控件详解
开发语言·c++·qt
iCxhust1 小时前
Prj10--8088单板机C语言8259测试(1)
c语言·开发语言
крон4 小时前
【Auto.js例程】华为备忘录导出到其他手机
开发语言·javascript·智能手机
zh_xuan5 小时前
c++ 单例模式
开发语言·c++·单例模式
老胖闲聊5 小时前
Python Copilot【代码辅助工具】 简介
开发语言·python·copilot
Blossom.1185 小时前
使用Python和Scikit-Learn实现机器学习模型调优
开发语言·人工智能·python·深度学习·目标检测·机器学习·scikit-learn
曹勖之6 小时前
基于ROS2,撰写python脚本,根据给定的舵-桨动力学模型实现动力学更新
开发语言·python·机器人·ros2
豆沙沙包?6 小时前
2025年- H77-Lc185--45.跳跃游戏II(贪心)--Java版
java·开发语言·游戏