最近在学习Qt,遇到很多不认识的类,学得比较迷茫,跟着教程做了一个电子时钟,左键摁住可以在界面上拖动,右键点击可以将其关闭。
以下是鄙人的学习代码,如果有错误,还敬请诸位学界泰斗斧正
#include "digiclock.h"
#include <QTimer>
#include <QTime>
#include <QMouseEvent>
DigiClock::DigiClock(QWidget *parent):QLCDNumber (parent)
{
//设置时钟背景
QPalette p=palette();//调色板
p.setColor(QPalette::Window,Qt::yellow);
setPalette(p); //这三句完成电子时钟的窗体背景色的设置
setWindowFlags(Qt::FramelessWindowHint); //设置窗体标识,此处设置为没有边框的和标题栏的窗体
setWindowOpacity(0.5); //设置 窗体的透明度,值越小越透明
QTimer *timer=new QTimer(this); //新建一个定时器对象
connect(timer,SIGNAL(timeout()),this,SLOT(showTime())); //连接定时器的timeout()信号和槽函数showTime()
timer->start(1000); //以1000ms为周期启动定时器
showTime(); //初始时间显示
resize(500,300); //设置窗口大小
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) //按住左键跟随拖动,按下右键关闭窗口
{
dragPositon=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()-dragPositon);
event->accept();
}
}