digiclock.h
#ifndef DIGICLOCK_H #define DIGICLOCK_H #include <QLCDNumber> #include <QPoint> class DigiClock : public QLCDNumber { Q_OBJECT public: DigiClock(QWidget *parent = 0); ~DigiClock(); void mousePressEvent(QMouseEvent *); void mouseMoveEvent(QMouseEvent *); public slots: void showTime(); private: QPoint dragPosition; //鼠标点击位置相对窗体左上角的偏移量 bool showColon; //是否显示“:” }; #endif // CLOCK_H
digiclock.cpp
#include "digiclock.h" #include <QPalette> #include <QTimer> #include <QTime> #include <QMouseEvent> DigiClock::DigiClock(QWidget *parent) : QLCDNumber(parent) { QPalette plt; //实例化调色板对象 plt.setColor(QPalette::Window,Qt::blue); setPalette(plt); setWindowFlags(Qt::FramelessWindowHint); setWindowOpacity(0.5); //设置不透明度 QTimer *timer = new QTimer(this); connect(timer,SIGNAL(timeout()),this,SLOT(showTime())); timer->start(1000); showTime(); resize(150,60); showColon = true; } DigiClock::~DigiClock() { } 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 * e) { if (e->button() == Qt::LeftButton) { dragPosition = e->globalPos() - frameGeometry().topLeft(); e->accept(); } if(e->button() == Qt::RightButton) { close(); } } void DigiClock::mouseMoveEvent(QMouseEvent * e) { if(e->buttons() & Qt::LeftButton) { move(e->globalPos() - dragPosition); e->accept(); } }