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

运行如下:

相关推荐
流星白龙1 小时前
【Qt】7.信号和槽_connect函数用法(2)
java·数据库·qt
金涛03191 小时前
QT-day2,信号和槽
开发语言·qt·命令模式
R-G-B7 小时前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长7 小时前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
史迪奇_xxx7 小时前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_801252228 小时前
Java中的反射
java·开发语言
Kiri霧8 小时前
Rust开发环境搭建
开发语言·后端·rust
weixin-a153003083168 小时前
[数据抓取-1]beautifulsoup
开发语言·python·beautifulsoup
小杨同学yx9 小时前
有关maven的一些知识点
java·开发语言
重生之我要当java大帝9 小时前
java微服务-尚医通-编写医院设置接口下
java·开发语言·sql