中間的冒號是一秒閃爍一次
新建一個繼承自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(按下時候)】
拖動的位置減去上一次位置就計算出來左上角應該移動的位置差。