详解QTimer与QTime如何实现电子时钟

发布时间:2020-07-20 16:10:57 作者:小猪
来源:亿速云 阅读:285

小编这次要给大家分享的是详解QTimer与QTime如何实现电子时钟,文章内容丰富,感兴趣的小伙伴可以来了解一下,希望大家阅读完这篇文章之后能够有所收获。

使用QLCDNumber控件进行显示

QLCDNumber控件默认只显示5个字符,可以使用setDigitCount(int size)进行设置显示个数

使用Display(QString str) 设置显示内容

该函数拥有多个重载,字符 整型 浮点型都可以作为参数 

效果图:

 详解QTimer与QTime如何实现电子时钟

代码:头文件

#include <QLCDNumber>
 
class NumClock : public QLCDNumber
{
 Q_OBJECT
public:
 explicit NumClock(QWidget *parent = nullptr);
 void mousePressEvent(QMouseEvent *event);
 void mouseMoveEvent(QMouseEvent *event);
 
signals:
 
public slots:
 void updateTime();
 
private:
 QTimer * timer;
 QPoint mouseOfPonit; // 鼠标坐标跟窗口左上角坐标的偏移值
 bool showColon;    //是否显示:
};

cpp文件:

#include "numclock.h"
#include <QTimer>
#include <QTime>
#include <QMouseEvent>
#include <QDebug>
 
NumClock::NumClock(QWidget *parent) : QLCDNumber(parent)
{
 timer = new QTimer(this);
 timer->setTimerType(Qt::PreciseTimer); // 设置精度为较高精度,差距在毫秒内
 timer->start(1000);
 connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()),Qt::QueuedConnection);
 
 setWindowFlag(Qt::FramelessWindowHint); //没有面板边框标题栏的窗体
 setWindowOpacity(0.5); //设置窗口的透明度
 
 showColon = true;
 
 this->setDigitCount(8);
 resize(150, 100);
 
 updateTime();
 
 
 setAttribute(Qt::WA_DeleteOnClose);
}
 
void NumClock::mousePressEvent(QMouseEvent *event)
{
 if(event->button() == Qt::LeftButton){
  mouseOfPonit = event->globalPos() - this->pos();
  event->accept();
 }else{
  close();
 }
}
 
void NumClock::mouseMoveEvent(QMouseEvent *event)
{
 if(event->buttons() & Qt::LeftButton){
  move(event->globalPos() - mouseOfPonit);
  event->accept();
 }
}
 
void NumClock::updateTime()
{
 QString timeStr = QTime::currentTime().toString("hh:mm:ss");
 if(showColon){
  timeStr = timeStr.replace(QString(":"), QString(" "));
  qDebug() << timeStr;
  showColon = false;
 }else{
  timeStr = timeStr.replace(QString(" "), QString(":"));
  showColon = true;
  qDebug() << timeStr;
 }
 display(timeStr);
}

看完这篇关于详解QTimer与QTime如何实现电子时钟的文章,如果觉得文章内容写得不错的话,可以把它分享出去给更多人看到。

推荐阅读:
  1. [180511]基于QTime类和QTimer类实现的计时器
  2. 怎么在PyQt5中利用QTimer实现一个电子时钟

免责声明:本站发布的内容(图片、视频和文字)以原创、转载和分享为主,文章观点不代表本网站立场,如果涉及侵权请联系站长邮箱:is@yisu.com进行举报,并提供相关证据,一经查实,将立刻删除涉嫌侵权内容。

qtimer qtime tim

上一篇:php、nignx虚拟主机配置

下一篇:第八节 比较操作符

相关阅读

您好,登录后才能下订单哦!

密码登录
登录注册
其他方式登录
点击 登录注册 即表示同意《亿速云用户服务条款》