QT5电子时钟

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

QT5电子时钟

KevinQUI   2022-06-28 我要评论

一、电子时钟的显示

效果如下:

电子时钟显示

二、新建工程

Widgets Application项目名位clock,基础类位QDialog,取消创建UI界面的勾选框,项目名右击添加新文件

在弹出的对话框中选择“C++ Class”,Base class基础类名“QLCDNumber”,class name命名为digiclock,点击完成。

三、编辑digiclock.h文件

#ifndef DIGICLOCK_H
#define DIGICLOCK_H
#include <QLCDNumber>
 
class DigiClock : public QLCDNumber
{
public:
    DigiClock(QWidget *parent=0);
    void mousePressEvent(QMouseEvent *);
    void mouseMoveEvent(QMouseEvent *);
private slots:
    void showTime();//显示槽函数
 
private:
    QPoint dragPosition;//相对位置偏移
    bool showColon;//是否显示“:”
    QTimer *mtimer;
};
 
#endif // DIGICLOCK_H

四、编辑digiclock.cpp文件

#include "digiclock.h"
#include <QTime>
#include <QTimer>
#include <QMouseEvent>
#include <QDebug>
 
DigiClock::DigiClock(QWidget *parent):QLCDNumber(parent)
{
    QPalette p = palette();//
    p.setColor(QPalette::Window,Qt::blue);
    setPalette(p);//设置窗体颜色
    setWindowFlags(Qt::FramelessWindowHint);//窗体设置位无边框
    setWindowOpacity(0.5);//设置透明度
    mtimer = new QTimer(this);//new 定时器对象
    //下列方法1不可以定时
    //connect(mtimer,SIGNAL(timeout()),this,SLOT(showTime()));
    //下列方法2可以实现定时
    connect(mtimer,&QTimer::timeout,[=](){showTime();});   
    if(mtimer->isActive()==false)//定时器检查激活状态
    {
    mtimer->start(1000);//启动
    }
    showTime();//槽函数
    resize(300,60);
    showColon=true;
}
void DigiClock::showTime()
{
    QTime time1 = QTime::currentTime();//获取当前时间
    QString text = time1.toString("hh:mm:ss");
    this->setDigitCount(8);//设置显示长度
 
    if(showColon)
    {
        text[2]=':';
        text[5]=':';
        showColon=false;
    }else
    {
        text[2]=' ';
        text[5]=' ';
        showColon=true;
    }
     //qDebug()<<text;
     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();
    }
}

五、编辑主函数

#include "dialog.h"
 
#include <QApplication>
#include "digiclock.h"
 
int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    DigiClock w;
    w.show();
    return a.exec();
}

六、总结

调试方法1时,connect(mtimer,SIGNAL(timeout()),this,SLOT(showTime()));不能实现定时的效果,纠结了好一阵,还是没发现问题,可能时QT书写形式更新了?

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们