QTime类的使用(电子钟)

一、建立头文件didiclock.h,头文件中的代码如下

#ifndef DIGICLOCK_H
#define DIGICLOCK_H

#include <QLCDNumber>

class DigiClock : public QLCDNumber
{
    
    
public:
    DigiClock(QWidget *parent=0);
    void mousePressEvent(QMouseEvent *);
    void mouseMoveEvent(QMouseEvent *);

public slots:
    void showTime();
private:
    QPoint dragPosition; //保存鼠标点相对电子时钟窗体左上角的偏移值
    bool showColon; //用于显示时间时是否显示“:”
};

#endif // DIGICLOCK_H

二、建立头文件didiclock.cpp,代码如下

#include "digiclock.h"

#include<QTimer>
#include<QTime>
#include<QMouseEvent>

DigiClock::DigiClock(QWidget *parent)
    :QLCDNumber(parent)
{
    
    
    QPalette p=palette();
    p.setColor(QPalette::Window,Qt::red); //电子钟窗体背景色设置为红色
    setPalette(p);

    setWindowFlags(Qt::FramelessWindowHint); //设置窗体为一个没有面板边框和标题栏的窗体

    setWindowOpacity(0.5); //设置窗体的透明度为0.5,即半透明

    QTimer *timer=new QTimer(this); //新建定时器对象
    connect(timer,SIGNAL(timeout()),this,SLOT(showtime()));
    timer->start(1000); //以1000毫秒为周期启动定时器
    showTime(); //初试时间显示
    resize(300,120); //设置电子钟显示的尺寸
    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();
    }
    if(event->button()==Qt::RightButton)
    {
    
    
        close();
    }
}

void DigiClock::mouseMoveEvent(QMouseEvent *event)
{
    
    
    if(event->buttons()&Qt::LeftButton)
    {
    
    
        move(event->globalPos()-dragPosition);
        event->accept();
    }
}

三、main.cpp中代码

#include "dialog.h"

#include <QApplication>
#include<digiclock.h>

int main(int argc, char *argv[])
{
    
    
    QApplication a(argc, argv);
//   Dialog w;
//   w.show();
    DigiClock clock;
    clock.show();
    return a.exec();
}

四、运行效果图
在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_27538633/article/details/109151425