今天完成一个实时显示时间的小demo
先上DJ先上DJ
先看一下效果
以两种形式显示当前具体时间
先附上代码,再总结一下核心代码
(1) myweather.ui文件
创建一个Label,ObjectName值为text;创建一个LCD Number,ObjectName为lcd。
分别用于两种形式的显示
(2) myweather.h文件
#ifndef MYWEATHER_H
#define MYWEATHER_H#include <QMainWindow>QT_BEGIN_NAMESPACE
namespace Ui { class MyWeather; }
QT_END_NAMESPACEclass MyWeather : public QMainWindow
{Q_OBJECTpublic:MyWeather(QWidget *parent = nullptr);~MyWeather();private:Ui::MyWeather *ui;
public slots:void timerUpdata(void);
};
#endif // MYWEATHER_H
这里声明了一个槽函数,用于处理 时间显示事件
(3)myweather.cpp
#include "myweather.h"
#include "ui_myweather.h"
#include <QFont>
#include <QTime>
#include <QTimer>
#include <qdatetime.h>
MyWeather::MyWeather(QWidget *parent): QMainWindow(parent), ui(new Ui::MyWeather)
{ui->setupUi(this);QTimer *timer = new QTimer(this);connect(timer,SIGNAL(timeout()),this,SLOT(timerUpdata()));timer->start(1000);
}MyWeather::~MyWeather()
{delete ui;
}
void MyWeather::timerUpdata()
{QFont font("Microsoft YaHei",20,50);QDateTime time = QDateTime::currentDateTime();QString str = time.toString("yyyy-MM-dd hh:mm:ss dddd");QString str1 = time.toString("yyyy-MM-dd hh:mm:ss");ui -> text ->setFont(font);this -> ui->text->setText(str);//ui->text->show();ui -> lcd -> display(str1);
}
涉及知识点:
a. 信号和槽
使用connect()函数,创建信号和槽的相对应关系
(connect()函数的写法有三种,具体的话自己可以查一下,与QT的版本有关,不用拘泥于特定的形式)
b.定时器
QTimer为QT中的一个定时器类,timer->start(1000)用于设置定时器的定时周期为1000ms,设置之后,每1000ms就会发射定时器的timeout()信号,那么在connect()函数中建立起关联的槽函数,就会在每次信号触发时进行相应的工作
c. QFont
用于控制QT控件的文字属性,具体用法可自行搜索,这里对用到的属性做简单介绍
d.QDateTime
QDateTime::currentDateTime();//获取系统现在的时间
QFont font ( “Microsoft YaHei”, 20, 50);
//第一个属性是字体(微软雅黑),第二个是大小,第三个是加粗(权重是75)
ui->label->setFont(font);常见权重
QFont::Light - 25 高亮
QFont::Normal - 50 正常
QFont::DemiBold - 63 半粗体
QFont::Bold - 75 粗体
QFont::Black - 87 黑体
(4)main.cpp
#include "myweather.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);MyWeather w;w.setWindowTitle("实时时钟系统");w.show();return a.exec();
}
大概内容就这样了,see you nala