中间的冒号是一秒闪烁一次
新建一个继承自QLCDNumber的类
头文件:
#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
#include "digiclock.h" #include <QTime> #include <QTimer> #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); QTimer *timer=new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(ShowTime())); timer->start(500); 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(); } else if(event->button()==Qt::RightButton) { close(); } } void DIgiClock::mouseMoveEvent(QMouseEvent *event) { move(event->globalPos()-dragPosition); event->accept(); }
上述代码主要有三点:
1,显示时间:
QTimer *timer=new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(ShowTime())); timer->start(500);每隔500毫秒调用一下ShowTime()槽函数。
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); }获取当前时间,然后放到QString中,然后调用父类方法display出来,这里的QString就有限制了,只能是QLCDNumber能显示的内容才行。
其中中间冒号间歇出现。
2,响应鼠标按下
void DIgiClock::mousePressEvent(QMouseEvent *event) { if(event->button()==Qt::LeftButton) { dragPosition=event->globalPos()-frameGeometry().topLeft(); event->accept(); } else if(event->button()==Qt::RightButton) { close(); } }
左键记录按下的位置,右键关闭
3,响应鼠标拖动
void DIgiClock::mouseMoveEvent(QMouseEvent *event) { move(event->globalPos()-dragPosition); event->accept(); }利用move函数将程序移动到指定位置,由于是窗口左上角移动到什么地方,所以这里做了计算。
计算内容应该是拖动的位置减去上一次位置的差加上左上角位置:
frameGeometry().topLeft()+【event->globalPos(当前位置)-event->globalPos(按下时候)】