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

运行如下:

相关推荐
网络大镖客几秒前
JavaScript高级进阶(五)
开发语言·前端·javascript
API小爬虫21 分钟前
利用 Python 爬虫按关键字搜索 1688 商品详情:实战指南
开发语言·爬虫·python
不当菜虚困22 分钟前
JAVA设计模式——(九)工厂模式
java·开发语言·设计模式
柴郡猫乐园25 分钟前
智能指针之设计模式5
开发语言·设计模式·智能指针
IT技术员27 分钟前
【Java学习】Java的CGLIB动态代理:通俗解释与使用指南
java·开发语言·学习
IvanCodes37 分钟前
Java 基础--流程控制语句
java·开发语言
白总Server44 分钟前
智能座舱架构中芯片算力评估
linux·运维·服务器·开发语言·ai·架构·bash
wjm0410061 小时前
C++日更八股--first
java·开发语言·c++
wei3872452322 小时前
java练习2
java·开发语言·python
我的golang之路果然有问题2 小时前
案例速成GO+Socket,个人笔记
开发语言·笔记·后端·websocket·学习·http·golang