程序
继承QLCDNumber类重新定义鼠标点击和鼠标移动事件。
//.h
#ifndef DIGICLOCK_H
#define DIGICLOCK_H
#include<QLCDNumber>
class DigiClock : public QLCDNumber
{
Q_OBJECT
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<QTimer>
#include<QTime>
#include<QMouseEvent>
#include<QDebug>
DigiClock::DigiClock(QWidget *parent):QLCDNumber(parent)
{
/*设置时钟背景*/
QPalette p=palette();
//将背景设置为蓝色
p.setColor(QPalette::Window,Qt::blue);
setPalette(p);
setWindowFlags(Qt::FramelessWindowHint);//设置窗体标识
setWindowOpacity(0.5);//设置窗体半透明
QTimer *timer=new QTimer(this);//新建一个定时器对象
connect(timer,SIGNAL(timeout()),this,SLOT(showTime()));//连接定时器的timeout信号和showTime
timer->start(1000);//以1000ms为周期启动定时器
showTime();
resize(150,60);//是指电子时钟的尺寸
showColon=true;
}
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();
}
}
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);
}