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

运行如下:

相关推荐
沉默媛17 分钟前
如何安装python以及jupyter notebook
开发语言·python·jupyter
_Chipen1 小时前
C++基础问题
开发语言·c++
止观止1 小时前
JavaScript对象创建9大核心技术解析
开发语言·javascript·ecmascript
screenCui3 小时前
macOS运行python程序遇libiomp5.dylib库冲突错误解决方案
开发语言·python·macos
linux kernel3 小时前
第七讲:C++中的string类
开发语言·c++
玩代码3 小时前
Java线程池原理概述
java·开发语言·线程池
泰勒疯狂展开3 小时前
Java研学-MongoDB(三)
java·开发语言·mongodb
zzywxc7874 小时前
AI技术通过提示词工程(Prompt Engineering)正在深度重塑职场生态和行业格局,这种变革不仅体现在效率提升,更在重构人机协作模式。
java·大数据·开发语言·人工智能·spring·重构·prompt
高hongyuan4 小时前
Go语言教程-占位符及演示代码
开发语言·后端·golang
她说人狗殊途4 小时前
多线程 JAVA
java·开发语言