QTime的currentTime():用于获取当前的系统时间;
QTime 的toString():用于将获取的当前时间转换为字符串类型。
为了便于显示,toString()函数的参数需指定转换后时间的显示格式。
显示格式有如下几种:
(1)H/h: 小时(若使用H表示小时,则无论何时都以24小时制显示小时;若使用h表示小时,则当同时指定AM/PM时,采用12 小时制显示小时,其他情况下仍采用24小时制进行显示)
(2)m:分
(3)s:秒
(4)AP/A:显示AM或PM
(5)Ap/a:显示am或pm
下面以代码形式介绍具体用法:
头文件:
#ifndef DIGICLOCK_H
#define DIGICLOCK_H
#include<QLCDNumber>
#include<QTime>
#include<QTimer>
class DigiClock : public QLCDNumber
{
public:
DigiClock(QWidget *parent=0);
void mousePressEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
public slots:
void showTime();
private:
QPoint dragPosition;
bool showColon;
};
#endif // DIGICLOCK_H
cpp文件:
#include "digiclock.h"
#include<QMouseEvent>
DigiClock::DigiClock(QWidget *parent):QLCDNumber(parent)
{
QPalette p=palette();
p.setColor(QPalette::Window,Qt::blue);//设置窗体的颜色
setPalette(p);//将调色板得以运用
setWindowFlags(Qt::FramelessWindowHint);
setWindowOpacity(0.5);
//showTime();
QTimer *timer=new QTimer(this);
connect(timer,SIGNAL(timeout()),this,SLOT(showTime()));
timer->start(1000);
showColon=true;
showTime();
resize(150,60);
//showColon=true;
}
void DigiClock::showTime()
{
QTime time=QTime::currentTime();
QString text=time.toString("hh:mm");
if(showColon)
{
text[2]=':';
showColon=false;
}
else
{
text[2]=';';
showColon=true;
}
display(text);
}
void DigiClock::mousePressEvent(QMouseEvent *event)
{
if(event->button()==Qt::LeftButton)
{
dragPosition=event->globalPos()-frameGeometry().topLeft();
event->accept();
}
if(event->button()==Qt::RightButton)
{
close();
}
}
void DigiClock::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons()&Qt::LeftButton)
{
move(event->globalPos()-dragPosition);
event->accept();
}
}
main函数的内容为:
#include "dialog.h"
#include <QApplication>
#include"digiclock.h"
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
DigiClock clock;
clock.show();
//Dialog w;
// w.show();
return a.exec();
}
展示的结果如下图所示: