QT5实现电子时钟

Maeve ·
更新时间:2024-09-20
· 25 次阅读

本文实例为大家分享了QT5实现电子时钟的具体代码,供大家参考,具体内容如下

一、电子时钟的显示

效果如下:

电子时钟显示

二、新建工程

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书写形式更新了?



qt5 电子

需要 登录 后方可回复, 如果你还没有账号请 注册新账号