【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.运行

运行如下:

相关推荐
代码or搬砖29 分钟前
Java集合-Set讲解
java·开发语言
艾上编程30 分钟前
第三章——爬虫工具场景之Python爬虫实战:学术文献摘要爬取,助力科研高效进行
开发语言·爬虫·python
明洞日记37 分钟前
【数据结构手册008】STL容器完全参考指南
开发语言·数据结构·c++
jllllyuz1 小时前
matlab使用B样条进行曲线曲面拟合
开发语言·matlab
ku_code_ku2 小时前
python bert_score使用本地模型的方法
开发语言·python·bert
小马哥编程2 小时前
【软考架构】滑动窗口限流算法的原理是什么?
java·开发语言·架构
水煎包V:YEDIYYDS8882 小时前
QT QML 实现的摇杆按钮,类似王者荣耀 左边方向导航键
qt·qml·摇杆按钮·导航键
云栖梦泽2 小时前
鸿蒙数据持久化实战:构建本地存储与云同步系统
开发语言·鸿蒙系统
wjs20242 小时前
《Ionic 侧栏菜单》
开发语言
祁思妙想2 小时前
linux常用命令
开发语言·python