Qt编写自定义控件19-图片背景时钟

简介: 一、前言图片背景时钟控件,是全套控件中唯一的几个贴图的控件,这个背景要是不贴图,会画到猝死,必须用美工做好的图贴图作为背景,此控件以前学C#的时候写过,后面在写Qt控件的过程中把他移植过来了,其实画法完全一模一样,我能说连代码我都是直接复制粘贴过来改改的吗?所以有过多年编程经验的程序员们都知道,编程都是一通百通的,只要掌握好了一门,或者精通了一门,其他都是水到渠成的事情,基本上学习个把星期都能直接撸的那种,配合F1帮助文档和官方手册,直接手撸起来(各位别多想,是指撸代码)。

一、前言

图片背景时钟控件,是全套控件中唯一的几个贴图的控件,这个背景要是不贴图,会画到猝死,必须用美工做好的图贴图作为背景,此控件以前学C#的时候写过,后面在写Qt控件的过程中把他移植过来了,其实画法完全一模一样,我能说连代码我都是直接复制粘贴过来改改的吗?所以有过多年编程经验的程序员们都知道,编程都是一通百通的,只要掌握好了一门,或者精通了一门,其他都是水到渠成的事情,基本上学习个把星期都能直接撸的那种,配合F1帮助文档和官方手册,直接手撸起来(各位别多想,是指撸代码)。
贴图的控件都很简单,直接drawimage完事,本控件除了支持多种背景风格样式以外,还特意增加了指针走动风格样式,直接鼠标右键切换风格等。

二、实现的功能

  • 1:支持鼠标右键切换风格
  • 2:支持设置四种背景风格样式
  • 3:支持四种秒针走动风格样式
  • 4:增加设置时间接口

三、效果图

imageclock

四、头文件代码

#ifndef IMAGECLOCK_H
#define IMAGECLOCK_H

/**
 * 图片时钟控件 作者:feiyangqingyun(QQ:517216493) 2016-11-4
 * 1:支持鼠标右键切换风格
 * 2:支持设置四种背景风格样式
 * 3:支持四种秒针走动风格样式
 * 4:增加设置时间接口
 */

#include <QWidget>

#ifdef quc
#if (QT_VERSION < QT_VERSION_CHECK(5,7,0))
#include <QtDesigner/QDesignerExportWidget>
#else
#include <QtUiPlugin/QDesignerExportWidget>
#endif

class QDESIGNER_WIDGET_EXPORT ImageClock : public QWidget
#else
class ImageClock : public QWidget
#endif

{
    Q_OBJECT
    Q_ENUMS(ClockStyle)
    Q_ENUMS(SecondStyle)

    Q_PROPERTY(ClockStyle clockStyle READ getClockStyle WRITE setClockStyle)
    Q_PROPERTY(SecondStyle secondStyle READ getSecondStyle WRITE setSecondStyle)

public:
    enum ClockStyle {
        ClockStyle_Trad = 0,        //黑色风格
        ClockStyle_System = 1,      //银色风格
        ClockStyle_Modern = 2,      //红色风格
        ClockStyle_Flower = 3       //花瓣风格
    };

    enum SecondStyle {
        SecondStyle_Normal = 0,     //普通效果
        SecondStyle_Spring = 1,     //弹簧效果
        SecondStyle_Continue = 2,   //连续效果
        SecondStyle_Hide = 3        //隐藏效果
    };

    explicit ImageClock(QWidget *parent = 0);
    ~ImageClock();

protected:
    void paintEvent(QPaintEvent *);
    void drawBg(QPainter *painter);
    void drawHour(QPainter *painter);
    void drawMin(QPainter *painter);
    void drawSec(QPainter *painter);
    void drawDot(QPainter *painter);

private:
    ClockStyle clockStyle;      //背景样式
    SecondStyle secondStyle;    //秒针走动样式

    QImage clockBg;             //主背景
    QImage clockHour;           //时钟背景
    QImage clockMin;            //分钟背景
    QImage clockSec;            //秒钟背景
    QImage clockDot;            //中间点背景
    QImage clockHighlights;     //高亮背景

    QStringList imageNames;     //图片名称集合

    QTimer *timer;              //定时器计算时间
    int hour, min, sec, msec;   //时分秒毫秒

    QTimer *timerSpring;        //定时器显示弹簧效果
    double angleSpring;         //弹簧角度

    QAction *action_secondstyle;//秒针样式右键菜单

private Q_SLOTS:
    void doAction();
    void updateTime();
    void updateSpring();

public:
    ClockStyle getClockStyle()      const;
    SecondStyle getSecondStyle()    const;
    QSize sizeHint()                const;
    QSize minimumSizeHint()         const;

public Q_SLOTS:
    //设置图片背景时钟样式
    void setClockStyle(const ClockStyle &clockStyle);
    //设置秒针走动样式
    void setSecondStyle(const SecondStyle &secondStyle);
    //设置系统时间
    void setSystemDateTime(const QString &year, const QString &month, const QString &day,
                           const QString &hour, const QString &min, const QString &sec);
};

#endif // IMAGECLOCK_H

五、完整代码

#pragma execution_character_set("utf-8")

#include "imageclock.h"
#include "qpainter.h"
#include "qtimer.h"
#include "qdatetime.h"
#include "qmath.h"
#include "qaction.h"
#include "qprocess.h"
#include "qdebug.h"

ImageClock::ImageClock(QWidget *parent): QWidget(parent)
{
    setFont(QFont("Microsoft Yahei", 9));

    QAction *action_trad = new QAction("黑色风格", this);
    connect(action_trad, SIGNAL(triggered(bool)), this, SLOT(doAction()));
    this->addAction(action_trad);

    QAction *action_system = new QAction("银色风格", this);
    connect(action_system, SIGNAL(triggered(bool)), this, SLOT(doAction()));
    this->addAction(action_system);

    QAction *action_modern = new QAction("红色风格", this);
    connect(action_modern, SIGNAL(triggered(bool)), this, SLOT(doAction()));
    this->addAction(action_modern);

    QAction *action_flower = new QAction("花瓣风格", this);
    connect(action_flower, SIGNAL(triggered(bool)), this, SLOT(doAction()));
    this->addAction(action_flower);

    action_secondstyle = new QAction("弹簧效果", this);
    connect(action_secondstyle, SIGNAL(triggered(bool)), this, SLOT(doAction()));
    this->addAction(action_secondstyle);

    this->setContextMenuPolicy(Qt::ActionsContextMenu);

    imageNames << "trad" << "system" << "modern" << "flower";

    timer = new QTimer(this);
    timer->setInterval(1000);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateTime()));
    timer->start();

    timerSpring = new QTimer(this);
    timerSpring->setInterval(30);
    connect(timerSpring, SIGNAL(timeout()), this, SLOT(updateSpring()));
    angleSpring = 6.0 * (sec + (double)msec / 1000);

    setClockStyle(ClockStyle_System);
    setSecondStyle(SecondStyle_Normal);
    updateTime();
}

ImageClock::~ImageClock()
{
    if (timer->isActive()) {
        timer->stop();
    }

    if (timerSpring->isActive()) {
        timerSpring->stop();
    }
}

void ImageClock::paintEvent(QPaintEvent *)
{
    int width = this->width();
    int height = this->height();

    //绘制准备工作,启用反锯齿,启用图片平滑缩放
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);
    painter.setRenderHint(QPainter::SmoothPixmapTransform, true);

    //绘制背景
    drawBg(&painter);

    painter.translate(width / 2, height / 2);

    //绘制时钟指针 尺寸:13×129
    drawHour(&painter);
    //绘制分钟指针 尺寸:13×129
    drawMin(&painter);
    //绘制秒钟指针 尺寸:13×129
    drawSec(&painter);
    //绘制中心盖板
    drawDot(&painter);
}

void ImageClock::drawBg(QPainter *painter)
{
    painter->save();
    int pixX = rect().center().x() - clockBg.width() / 2;
    int pixY = rect().center().y() - clockBg.height() / 2;
    QPoint point(pixX, pixY);
    painter->drawImage(point, clockBg);
    painter->drawImage(point, clockHighlights);
    painter->restore();
}

void ImageClock::drawHour(QPainter *painter)
{
    painter->save();
    painter->rotate(30.0 * ((hour + min / 60.0)));
    painter->drawImage(QRect(-6.5, -64.5, 13, 129), clockHour);
    painter->restore();
}

void ImageClock::drawMin(QPainter *painter)
{
    painter->save();
    painter->rotate(6.0 * (min + sec / 60.0));
    painter->drawImage(QRect(-6.5, -64.5, 13, 129), clockMin);
    painter->restore();
}

void ImageClock::drawSec(QPainter *painter)
{
    if (secondStyle == SecondStyle_Hide) {
        return;
    }

    painter->save();
    painter->rotate(angleSpring);
    painter->drawImage(QRect(-6.5, -64.5, 13, 129), clockSec);
    painter->restore();
}

void ImageClock::drawDot(QPainter *painter)
{
    painter->save();
    painter->drawImage(QRect(-6.5, -64.5, 13, 129), clockDot);
    painter->restore();
}

void ImageClock::doAction()
{
    QAction *action = (QAction *)sender();
    QString str = action->text();

    if (str == "黑色风格") {
        setClockStyle(ClockStyle_Trad);
    } else if (str == "银色风格") {
        setClockStyle(ClockStyle_System);
    } else if (str == "红色风格") {
        setClockStyle(ClockStyle_Modern);
    } else if (str == "花瓣风格") {
        setClockStyle(ClockStyle_Flower);
    } else if (str == "弹簧效果") {
        action->setText("连续效果");
        setSecondStyle(SecondStyle_Spring);
    } else if (str == "连续效果") {
        action->setText("隐藏效果");
        setSecondStyle(SecondStyle_Continue);
    } else if (str == "隐藏效果") {
        action->setText("普通效果");
        setSecondStyle(SecondStyle_Hide);
    } else if (str == "普通效果") {
        action->setText("弹簧效果");
        setSecondStyle(SecondStyle_Normal);
    }
}

void ImageClock::updateTime()
{
    QTime now = QTime::currentTime();
    hour = now.hour();
    min = now.minute();
    sec = now.second();
    msec = now.msec();

    if (secondStyle != SecondStyle_Hide) {
        angleSpring = 6.0 * (sec + (double)msec / 1000);

        if (secondStyle == SecondStyle_Spring) {
            angleSpring += 5;
            timerSpring->start();
        }
    }

    update();
}

void ImageClock::updateSpring()
{
    angleSpring = 6.0 * (sec + (double)msec / 1000);
    update();
    timerSpring->stop();
}

ImageClock::ClockStyle ImageClock::getClockStyle() const
{
    return this->clockStyle;
}

ImageClock::SecondStyle ImageClock::getSecondStyle() const
{
    return this->secondStyle;
}

QSize ImageClock::sizeHint() const
{
    return QSize(130, 130);
}

QSize ImageClock::minimumSizeHint() const
{
    return QSize(130, 130);
}

void ImageClock::setClockStyle(const ClockStyle &clockStyle)
{
    if (this->clockStyle != clockStyle){
        QString imageName = imageNames.at(clockStyle);
        this->clockStyle = clockStyle;
        clockBg = QImage(QString(":/image/clock_%1.png").arg(imageName));
        clockHour = QImage(QString(":/image/clock_%1_h.png").arg(imageName));
        clockMin = QImage(QString(":/image/clock_%1_m.png").arg(imageName));
        clockSec = QImage(QString(":/image/clock_%1_s.png").arg(imageName));
        clockDot = QImage(QString(":/image/clock_%1_dot.png").arg(imageName));
        clockHighlights = QImage(QString(":/image/clock_%1_highlights.png").arg(imageName));
        update();
    }
}

void ImageClock::setSecondStyle(const SecondStyle &secondStyle)
{
    if (this->secondStyle != secondStyle){
        this->secondStyle = secondStyle;

        if (secondStyle == SecondStyle_Continue) {
            timer->setInterval(100);
        } else {
            timer->setInterval(1000);
        }

        if (secondStyle == SecondStyle_Spring) {
            action_secondstyle->setText("连续效果");
        } else if (secondStyle == SecondStyle_Continue) {
            action_secondstyle->setText("隐藏效果");
        } else if (secondStyle == SecondStyle_Hide) {
            action_secondstyle->setText("普通效果");
        } else if (secondStyle == SecondStyle_Normal) {
            action_secondstyle->setText("弹簧效果");
            updateTime();
            return;
        }

        update();
    }
}

void ImageClock::setSystemDateTime(const QString &year, const QString &month, const QString &day,
                                   const QString &hour, const QString &min, const QString &sec)
{
#ifdef Q_OS_WIN
    QProcess p(0);
    p.start("cmd");
    p.waitForStarted();
    p.write(QString("date %1-%2-%3\n").arg(year).arg(month).arg(day).toLatin1());
    p.closeWriteChannel();
    p.waitForFinished(1000);
    p.close();
    p.start("cmd");
    p.waitForStarted();
    p.write(QString("time %1:%2:%3.00\n").arg(hour).arg(min).arg(sec).toLatin1());
    p.closeWriteChannel();
    p.waitForFinished(1000);
    p.close();
#else
    QString cmd = QString("date %1%2%3%4%5.%6").arg(month).arg(day).arg(hour).arg(min).arg(year).arg(sec);
    system(cmd.toLatin1());
    system("hwclock -w");
#endif
}

六、控件介绍

  1. 超过150个精美控件,涵盖了各种仪表盘、进度条、进度球、指南针、曲线图、标尺、温度计、导航条、导航栏,flatui、高亮按钮、滑动选择器、农历等。远超qwt集成的控件数量。
  2. 每个类都可以独立成一个单独的控件,零耦合,每个控件一个头文件和一个实现文件,不依赖其他文件,方便单个控件以源码形式集成到项目中,较少代码量。qwt的控件类环环相扣,高度耦合,想要使用其中一个控件,必须包含所有的代码。
  3. 全部纯Qt编写,QWidget+QPainter绘制,支持Qt4.6到Qt5.12的任何Qt版本,支持mingw、msvc、gcc等编译器,支持任意操作系统比如windows+linux+mac+嵌入式linux等,不乱码,可直接集成到Qt Creator中,和自带的控件一样使用,大部分效果只要设置几个属性即可,极为方便。
  4. 每个控件都有一个对应的单独的包含该控件源码的DEMO,方便参考使用。同时还提供一个所有控件使用的集成的DEMO。
  5. 每个控件的源代码都有详细中文注释,都按照统一设计规范编写,方便学习自定义控件的编写。
  6. 每个控件默认配色和demo对应的配色都非常精美。
  7. 超过130个可见控件,6个不可见控件。
  8. 部分控件提供多种样式风格选择,多种指示器样式选择。
  9. 所有控件自适应窗体拉伸变化。
  10. 集成自定义控件属性设计器,支持拖曳设计,所见即所得,支持导入导出xml格式。
  11. 自带activex控件demo,所有控件可以直接运行在ie浏览器中。
  12. 集成fontawesome图形字体+阿里巴巴iconfont收藏的几百个图形字体,享受图形字体带来的乐趣。
  13. 所有控件最后生成一个dll动态库文件,可以直接集成到qtcreator中拖曳设计使用。
  14. 目前已经有qml版本,后期会考虑出pyqt版本,如果用户需求量很大的话。

七、SDK下载

  • SDK下载链接:https://pan.baidu.com/s/1A5Gd77kExm8Co5ckT51vvQ 提取码:877p
  • 下载链接中包含了各个版本的动态库文件,所有控件的头文件,使用demo,自定义控件+属性设计器。
  • 自定义控件插件开放动态库dll使用(永久免费),无任何后门和限制,请放心使用。
  • 目前已提供26个版本的dll,其中包括了qt5.12.3 msvc2017 32+64 mingw 32+64 的。
  • 不定期增加控件和完善控件,不定期更新SDK,欢迎各位提出建议,谢谢!
  • widget版本(QQ:517216493)qml版本(QQ:373955953)三峰驼(QQ:278969898)。
  • 涛哥的知乎专栏 Qt进阶之路 https://zhuanlan.zhihu.com/TaoQt
  • 欢迎关注微信公众号【高效程序员】,C++/Python、学习方法、写作技巧、热门技术、职场发展等内容,干货多多,福利多多!
相关文章
|
5月前
|
计算机视觉 C++
基于Qt的简易图片浏览器设计与实现
基于Qt的简易图片浏览器设计与实现
232 1
|
5月前
|
存储 容器
QT中QListWidget实现QListWidgetItem图片和文字居中
在使用QT开发软件的过程中,很多时候使用QListWidget来实现列表项的功能,比如MS系统的功能模块菜单,如下面2张图所示,其中第一张图是带文字和图标的列表项,第二张图是纯图标的模式,在最近开发的平台客户端的某个功能模块都用上了。
784 0
|
3月前
|
数据安全/隐私保护 C++ 计算机视觉
Qt(C++)开发一款图片防盗用水印制作小工具
文本水印是一种常用的防盗用手段,可以将文本信息嵌入到图片、视频等文件中,用于识别和证明文件的版权归属。在数字化和网络化的时代,大量的原创作品容易被不法分子盗用或侵犯版权,因此加入文本水印成为了保护原创作品和维护知识产权的必要手段。 通常情况下,文本水印可以包含版权声明、制作者姓名、日期、网址等信息,以帮助识别文件的来源和版权归属。同时,为了增强防盗用效果,文本水印通常会采用字体、颜色、角度等多种组合方式,使得水印难以被删除或篡改,有效地降低了盗用意愿和风险。 开发人员可以使用图像处理技术和编程语言实现文本水印的功能,例如使用Qt的QPainter类进行文本绘制操作,将文本信息嵌入到图片中,
146 1
Qt(C++)开发一款图片防盗用水印制作小工具
|
2月前
|
计算机视觉
使用QT显示OpenCV读取的图片
使用QT显示OpenCV读取的图片
39 1
|
4月前
Qt绘图(线条、椭圆、矩形、图片滚动)
Qt绘图(线条、椭圆、矩形、图片滚动)
149 3
|
4月前
|
算法 计算机视觉
【Qt&OpenCV QGraphicsView显示OpenCV读入的图片】
【Qt&OpenCV QGraphicsView显示OpenCV读入的图片】
62 0
|
C++
Qt图片定时滚动播放器+透明过渡动画
解决:[QWidget::paintEngine: Should no longer be called QPainter::begin: Paint device returned engine == 0, type: 1] 需要在哪个控件上绘制,就要在哪个控件类中重写 paintEvent() ,所以本项目 需要使用自定义的MyQLabel继承QLabel
125 0
|
5月前
|
存储 C++ 开发者
QT基础【4-简易的图片查看程序】
QT基础【4-简易的图片查看程序】
|
5月前
|
小程序
Qt实现图片可拖拉
Qt实现图片可拖拉
|
5月前
Qt鼠标悬浮在图片上显示删除字样
Qt鼠标悬浮在图片上显示删除字样