直接上代码
#ifndef DIALOG_H
#define DIALOG_H
#include <QDialog>
#include <QLCDNumber>
//class Dialog : public QDialog
class Dialog : public QLCDNumber
{
Q_OBJECT
public:
Dialog(QWidget *parent = 0);
~Dialog();
void mousePressEvent(QMouseEvent *);
void mouseMoveEvent(QMouseEvent *);
public slots:
void showTime(); //显示当前的时间
private:
QPoint dragPosition; //保存鼠标点相对电子时钟窗体左上角的偏移值
bool showColon; //用于显示冒号
};
#endif // DIALOG_H
#include "dialog.h"
#include <QTime>
#include <QTimer>
#include <QMouseEvent>
Dialog::Dialog(QWidget *parent)
: QLCDNumber(parent)
{
//设置时钟背景
QPalette p=palette();
p.setColor(QPalette::Window, Qt::blue);
setPalette(p);
setWindowFlag(Qt::FramelessWindowHint); //设置窗体的标识,此处设置窗体为一个没有面板边框和标题栏的窗体
setWindowOpacity(0.5); //设置窗体的透明度为0.5
QTimer *timer = new QTimer(this); //新建一个定时器对象
connect(timer, &QTimer::timeout, this, &Dialog::showTime); //(d)
timer->start(1000); //设置以1000毫秒为周期的定时器
setDigitCount(8); //设置字符显示个数
showTime(); //初始时间显示
resize(160, 60); //设置电子时钟的显示尺寸
showColon = true; //初始化
}
Dialog::~Dialog()
{
}
void Dialog::showTime()
{
QTime time=QTime::currentTime();
QString text=time.toString("hh:mm:ss");
if(showColon)
{
text[2] = ':';
text[5] = ':';
showColon = false;
}
else
{
text[2] = ' ';
text[5] = ' ';
showColon = true;
}
display(text);
}
void Dialog::mousePressEvent(QMouseEvent *event)
{
if(event->button()==Qt::LeftButton)
{
dragPosition=event->globalPos()-frameGeometry().topLeft();
event->accept();
}
if(event->button()==Qt::RightButton)
{
close();
}
}
void Dialog::mouseMoveEvent(QMouseEvent *event)
{
if(event->buttons()&Qt::LeftButton)
{
move(event->globalPos()-dragPosition);
event->accept();
}
}
#include "dialog.h"
#include <QApplication>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
Dialog w;
w.show();
return a.exec();
}