综合实例-电子时钟
- 知识点
- digiclock.h
- digiclock.cpp
- main.cpp
- 运行图
知识点
setWindowOpacity(0.5);//设置窗体透明度
QTimer* Timer = new QTimer(this);//新建一个定时器
connect(Timer,SIGNAL(timeout()),this,SLOT(ShowTime()));
Timer->start(1000);//启动定时器
digiclock.h
#ifndef DIGICLOCK_H
#define DIGICLOCK_H#include <QDialog>
#include <QLCDNumber>class DigiClock : public QLCDNumber
{Q_OBJECTpublic:DigiClock(QWidget *parent = nullptr);~DigiClock();void mousePressEvent(QMouseEvent*);void mouseMoveEvent(QMouseEvent*);
public slots:void ShowTime();
private:QPoint DragPosition;//保存鼠标相对电子时钟窗体左上角的偏移值bool ShowColon;//用于显示事件是否显示":"};
#endif // DIGICLOCK_H
digiclock.cpp
#include "digiclock.h"
#include <QTimer>
#include <QTime>
#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(1000);//启动定时器ShowTime();//初始化时间显示resize(150,60);//设置窗口大小ShowColon = true;
}DigiClock::~DigiClock() {}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);}
main.cpp
#include "digiclock.h"#include <QApplication>int main(int argc, char *argv[])
{QApplication a(argc, argv);DigiClock w;w.show();return a.exec();
}