QT實現Digital Clock

QT實現Digital Clock

Demo 實現DigitalClock類,該類繼承自QLCDNumber,實現電子錶的界面和邏輯,核心邏輯爲藉助QTimer,定時更新空間界面。以下爲程序實現

digitalclock.h

#ifndef DIGITALCLOCK_H
#define DIGITALCLOCK_H

#include <QLCDNumber>

class QTimer;

class DigitalClock : public QLCDNumber
{
    Q_OBJECT

public:
    DigitalClock(QWidget *parent = 0);
    ~DigitalClock() {}

    QString FormatStr() const {return m_TimeFormatStr;}
    void setFormatStr(const QString &FormatStr = QString("hh:mm:ss"));
    void InitTimer(int millisecond = 1000);

private slots:
    void showTime();

private:
    QString m_TimeFormatStr;
    QTimer *m_Timer;
};

#endif // DIGITALCLOCK_H

digitalclock.cpp

#include "digitalclock.h"


#include <QTimer>
#include <QTime>

DigitalClock::DigitalClock(QWidget *parent)
    : QLCDNumber(parent)
{
    setWindowTitle("Digital Clock");
    setSegmentStyle(QLCDNumber::Flat);
    setFormatStr();

    InitTimer();

    showTime();

     Qt::WindowFlags f;
     f |= (Qt::MSWindowsFixedSizeDialogHint|Qt::FramelessWindowHint);
     setWindowFlags(f);//set window frameless
     move(0,0);//move to the top-left corner of screen

     setFixedSize(200, 60);//set windowsize to fixed size
}

void DigitalClock::showTime()
{
    QTime time = QTime::currentTime();
    QString str = time.toString(m_TimeFormatStr);
    display(str);
}

void DigitalClock::setFormatStr(const QString &FormatStr)
{
    m_TimeFormatStr = FormatStr;
    setDigitCount(m_TimeFormatStr.length());
}

void DigitalClock::InitTimer(int millisecond)
{
    m_Timer = new QTimer(this);
    m_Timer->start(millisecond);
    connect(m_Timer, SIGNAL(timeout()), this, SLOT(showTime()));
}

上面的代碼做了一些優化,比如:

     Qt::WindowFlags f;
     f |= (Qt::MSWindowsFixedSizeDialogHint|Qt::FramelessWindowHint);
     setWindowFlags(f);//set window frameless
     move(0,0);//move to the top-left corner of screen
    setFixedSize(200, 60);//set windowsize to fixed size

這段代碼設置程序窗口無邊框,大小固定且位置固定在屏幕左上角。所以構造函數的第一句設置窗口標題是看不到的:

 setWindowTitle("Digital Clock");

程序中

void DigitalClock::InitTimer(int millisecond)
{
    m_Timer = new QTimer(this);
    m_Timer->start(millisecond);
    connect(m_Timer, SIGNAL(timeout()), this, SLOT(showTime()));
}

該函數初始化一個定時器,默認間隔1000ms,使用connect()函數關聯定時器超時信號timeout()和界面更新函數showTime(),實現時間的更新。

connect(m_Timer, SIGNAL(timeout()), this, SLOT(showTime()));

運行效果:
這裏寫圖片描述

參考

QT Digital Clock Example

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章