C++版QT:电子时钟

发布时间:2024年01月23日

digiclock.h

#ifndef DIGICLOCK_H
#define DIGICLOCK_H
?
#include <QLCDNumber>
?
class DigiClock : public QLCDNumber
{
    Q_OBJECT
public:
    DigiClock(QWidget* parent = 0);
    void mousePressEvent(QMouseEvent*);
    void mouseMoveEvent(QMouseEvent*);
public slots:
    void showTime();                   //显示当前的时间
private:
    QPoint dragPosition;              //保存鼠标点相对电子时钟窗体左上角的偏移值
    bool showColon;                    //用于显示时间时是否显示“:”
};
?
#endif // DIGICLOCK_H
?

digiclock.cpp

#include "digiclock.h"
#include <QTimer>
#include <QTime>
#include <QMouseEvent>
?
DigiClock::DigiClock(QWidget* parent)
    :QLCDNumber(parent)
{
    QPalette p = palette();
    p.setColor(QPalette::Window, Qt::blue);
    setPalette(p);
?
    setWindowFlags(Qt::FramelessWindowHint);
?
    setWindowOpacity(0.5);
?
    QTimer* timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(showTime()));
    timer->start(1000);
    showTime();
    resize(150, 60);
    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 <QApplication>
#include "digiclock.h"
?
int main(int argc, char* argv[])
{
    QApplication a(argc, argv);
    DigiClock clock;
    clock.show();
?
    return a.exec();
}
?

文章来源:https://blog.csdn.net/T20151470/article/details/135759985
本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。