天天看點

Qt編寫自定義控件38-高亮按鈕

一、前言

高亮按鈕控件,既可以作為類似于交通訓示燈使用,也可以作為裝置狀态訓示燈使用,控件内置多套顔色風格,還可以自己設定顔色風格,按鈕可以增加文字顯示,非常适合需要在狀态裝置上顯示小量的文字展示,按鈕還可以開啟報警,開啟後會紅黑閃爍,也可以自定義設定報警的兩種顔色,除了預設是圓形外,還可以設定成矩形模式,控件寫好了作為獨立控件拖動使用,這樣的話可以将控件作為一個裝置,在地圖上拖動,使用者隻需要開啟拖動即可,不需要再自己編碼。

二、實作的功能

  • 1:可設定文本,居中顯示
  • 2:可設定文本顔色
  • 3:可設定外邊框漸變顔色
  • 4:可設定裡邊框漸變顔色
  • 5:可設定背景色
  • 6:可直接調用内置的設定 綠色/紅色/黃色/黑色/藍色 等公有槽函數
  • 7:可設定是否在容器中可移動,當成一個對象使用
  • 8:可設定是否顯示矩形
  • 9:可設定報警顔色+非報警顔色
  • 10:可控制啟動報警和停止報警,報警時閃爍

三、效果圖

Qt編寫自定義控件38-高亮按鈕

四、頭檔案代碼

#ifndef LIGHTBUTTON_H
#define LIGHTBUTTON_H

/**
 * 高亮發光按鈕控件 作者:feiyangqingyun(QQ:517216493) 2016-10-16
 * 1:可設定文本,居中顯示
 * 2:可設定文本顔色
 * 3:可設定外邊框漸變顔色
 * 4:可設定裡邊框漸變顔色
 * 5:可設定背景色
 * 6:可直接調用内置的設定 綠色/紅色/黃色/黑色/藍色 等公有槽函數
 * 7:可設定是否在容器中可移動,當成一個對象使用
 * 8:可設定是否顯示矩形
 * 9:可設定報警顔色+非報警顔色
 * 10:可控制啟動報警和停止報警,報警時閃爍
 */

#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 LightButton : public QWidget
#else
class LightButton : public QWidget
#endif

{
    Q_OBJECT
    Q_PROPERTY(QString text READ getText WRITE setText)
    Q_PROPERTY(QColor textColor READ getTextColor WRITE setTextColor)
    Q_PROPERTY(QColor alarmColor READ getAlarmColor WRITE setAlarmColor)
    Q_PROPERTY(QColor normalColor READ getNormalColor WRITE setNormalColor)

    Q_PROPERTY(QColor borderOutColorStart READ getBorderOutColorStart WRITE setBorderOutColorStart)
    Q_PROPERTY(QColor borderOutColorEnd READ getBorderOutColorEnd WRITE setBorderOutColorEnd)
    Q_PROPERTY(QColor borderInColorStart READ getBorderInColorStart WRITE setBorderInColorStart)
    Q_PROPERTY(QColor borderInColorEnd READ getBorderInColorEnd WRITE setBorderInColorEnd)
    Q_PROPERTY(QColor bgColor READ getBgColor WRITE setBgColor)

    Q_PROPERTY(bool canMove READ getCanMove WRITE setCanMove)
    Q_PROPERTY(bool showRect READ getShowRect WRITE setShowRect)
    Q_PROPERTY(bool showOverlay READ getShowOverlay WRITE setShowOverlay)
    Q_PROPERTY(QColor overlayColor READ getOverlayColor WRITE setOverlayColor)

public:
    explicit LightButton(QWidget *parent = 0);

protected:
    bool eventFilter(QObject *watched, QEvent *event);
    void paintEvent(QPaintEvent *);
    void drawBorderOut(QPainter *painter);
    void drawBorderIn(QPainter *painter);
    void drawBg(QPainter *painter);
    void drawText(QPainter *painter);
    void drawOverlay(QPainter *painter);

private:
    QString text;                   //文本
    QColor textColor;               //文字顔色
    QColor alarmColor;              //報警顔色
    QColor normalColor;             //正常顔色

    QColor borderOutColorStart;     //外邊框漸變開始顔色
    QColor borderOutColorEnd;       //外邊框漸變結束顔色
    QColor borderInColorStart;      //裡邊框漸變開始顔色
    QColor borderInColorEnd;        //裡邊框漸變結束顔色
    QColor bgColor;                 //背景顔色

    bool showRect;                  //顯示成矩形
    bool canMove;                   //是否能夠移動
    bool showOverlay;               //是否顯示遮罩層
    QColor overlayColor;            //遮罩層顔色

    QTimer *timerAlarm;             //定時器切換顔色

public:
    QString getText()               const;
    QColor getTextColor()           const;
    QColor getAlarmColor()          const;
    QColor getNormalColor()         const;

    QColor getBorderOutColorStart() const;
    QColor getBorderOutColorEnd()   const;
    QColor getBorderInColorStart()  const;
    QColor getBorderInColorEnd()    const;
    QColor getBgColor()             const;

    bool getCanMove()               const;
    bool getShowRect()              const;
    bool getShowOverlay()           const;
    QColor getOverlayColor()        const;

    QSize sizeHint()                const;
    QSize minimumSizeHint()         const;

public Q_SLOTS:
    //設定文本
    void setText(const QString &text);
    //設定文本顔色
    void setTextColor(const QColor &textColor);

    //設定報警顔色+正常顔色
    void setAlarmColor(const QColor &alarmColor);
    void setNormalColor(const QColor &normalColor);

    //設定外邊框漸變顔色
    void setBorderOutColorStart(const QColor &borderOutColorStart);
    void setBorderOutColorEnd(const QColor &borderOutColorEnd);

    //設定裡邊框漸變顔色
    void setBorderInColorStart(const QColor &borderInColorStart);
    void setBorderInColorEnd(const QColor &borderInColorEnd);

    //設定背景色
    void setBgColor(const QColor &bgColor);

    //設定是否可移動
    void setCanMove(bool canMove);
    //設定是否顯示矩形
    void setShowRect(bool showRect);
    //設定是否顯示遮罩層
    void setShowOverlay(bool showOverlay);
    //設定遮罩層顔色
    void setOverlayColor(const QColor &overlayColor);

    //設定為綠色
    void setGreen();
    //設定為紅色
    void setRed();
    //設定為黃色
    void setYellow();
    //設定為黑色
    void setBlack();
    //設定為灰色
    void setGray();
    //設定為藍色
    void setBlue();
    //設定為淡藍色
    void setLightBlue();
    //設定為淡紅色
    void setLightRed();
    //設定為淡綠色
    void setLightGreen();

    //設定報警閃爍
    void startAlarm();
    void stopAlarm();
    void alarm();
};

#endif // LIGHTBUTTON_H

           

五、核心代碼

#pragma execution_character_set("utf-8")

#include "lightbutton.h"
#include "qpainter.h"
#include "qevent.h"
#include "qtimer.h"
#include "qdebug.h"

LightButton::LightButton(QWidget *parent) : QWidget(parent)
{
    text = "";
    textColor = QColor(255, 255, 255);
    alarmColor = QColor(255, 107, 107);
    normalColor = QColor(10, 10, 10);

    borderOutColorStart = QColor(255, 255, 255);
    borderOutColorEnd = QColor(166, 166, 166);

    borderInColorStart = QColor(166, 166, 166);
    borderInColorEnd = QColor(255, 255, 255);

    bgColor = QColor(100, 184, 255);

    showRect = false;
    showOverlay = true;
    overlayColor = QColor(255, 255, 255);

    canMove = false;
    this->installEventFilter(this);

    timerAlarm = new QTimer(this);
    connect(timerAlarm, SIGNAL(timeout()), this, SLOT(alarm()));
    timerAlarm->setInterval(500);

    //setFont(QFont("Arial", 8));
}

bool LightButton::eventFilter(QObject *watched, QEvent *event)
{
    if (canMove) {
        static QPoint lastPnt;
        static bool pressed = false;
        QMouseEvent *mouseEvent = static_cast<QMouseEvent *>(event);

        if (mouseEvent->type() == QEvent::MouseButtonPress) {
            if (this->rect().contains(mouseEvent->pos()) && (mouseEvent->button() == Qt::LeftButton)) {
                lastPnt = mouseEvent->pos();
                pressed = true;
            }
        } else if (mouseEvent->type() == QEvent::MouseMove && pressed) {
            int dx = mouseEvent->pos().x() - lastPnt.x();
            int dy = mouseEvent->pos().y() - lastPnt.y();
            this->move(this->x() + dx, this->y() + dy);
        } else if (mouseEvent->type() == QEvent::MouseButtonRelease && pressed) {
            pressed = false;
        }
    }

    return QWidget::eventFilter(watched, event);
}

void LightButton::paintEvent(QPaintEvent *)
{
    int width = this->width();
    int height = this->height();
    int side = qMin(width, height);

    //繪制準備工作,啟用反鋸齒,平移坐标軸中心,等比例縮放
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing);

    if (showRect) {
        //繪制矩形區域
        painter.setPen(Qt::NoPen);
        painter.setBrush(bgColor);
        painter.drawRoundedRect(this->rect(), 5, 5);

        //繪制文字
        if (!text.isEmpty()) {
            QFont font;
            font.setPixelSize(side - 20);
            painter.setFont(font);
            painter.setPen(textColor);
            painter.drawText(this->rect(), Qt::AlignCenter, text);
        }
    } else {
        painter.translate(width / 2, height / 2);
        painter.scale(side / 200.0, side / 200.0);

        //繪制外邊框
        drawBorderOut(&painter);
        //繪制内邊框
        drawBorderIn(&painter);
        //繪制内部訓示顔色
        drawBg(&painter);
        //繪制居中文字
        drawText(&painter);
        //繪制遮罩層
        drawOverlay(&painter);
    }
}

void LightButton::drawBorderOut(QPainter *painter)
{
    int radius = 99;
    painter->save();
    painter->setPen(Qt::NoPen);
    QLinearGradient borderGradient(0, -radius, 0, radius);
    borderGradient.setColorAt(0, borderOutColorStart);
    borderGradient.setColorAt(1, borderOutColorEnd);
    painter->setBrush(borderGradient);
    painter->drawEllipse(-radius, -radius, radius * 2, radius * 2);
    painter->restore();
}

void LightButton::drawBorderIn(QPainter *painter)
{
    int radius = 90;
    painter->save();
    painter->setPen(Qt::NoPen);
    QLinearGradient borderGradient(0, -radius, 0, radius);
    borderGradient.setColorAt(0, borderInColorStart);
    borderGradient.setColorAt(1, borderInColorEnd);
    painter->setBrush(borderGradient);
    painter->drawEllipse(-radius, -radius, radius * 2, radius * 2);
    painter->restore();
}

void LightButton::drawBg(QPainter *painter)
{
    int radius = 80;
    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(bgColor);
    painter->drawEllipse(-radius, -radius, radius * 2, radius * 2);
    painter->restore();
}

void LightButton::drawText(QPainter *painter)
{
    if (text.isEmpty()) {
        return;
    }

    int radius = 100;
    painter->save();

    QFont font;
    font.setPixelSize(85);
    painter->setFont(font);
    painter->setPen(textColor);
    QRect rect(-radius, -radius, radius * 2, radius * 2);
    painter->drawText(rect, Qt::AlignCenter, text);
    painter->restore();
}

void LightButton::drawOverlay(QPainter *painter)
{
    if (!showOverlay) {
        return;
    }

    int radius = 80;
    painter->save();
    painter->setPen(Qt::NoPen);

    QPainterPath smallCircle;
    QPainterPath bigCircle;
    radius -= 1;
    smallCircle.addEllipse(-radius, -radius, radius * 2, radius * 2);
    radius *= 2;
    bigCircle.addEllipse(-radius, -radius + 140, radius * 2, radius * 2);

    //高光的形狀為小圓扣掉大圓的部分
    QPainterPath highlight = smallCircle - bigCircle;

    QLinearGradient linearGradient(0, -radius / 2, 0, 0);
    overlayColor.setAlpha(100);
    linearGradient.setColorAt(0.0, overlayColor);
    overlayColor.setAlpha(30);
    linearGradient.setColorAt(1.0, overlayColor);
    painter->setBrush(linearGradient);
    painter->rotate(-20);
    painter->drawPath(highlight);

    painter->restore();
}

QString LightButton::getText() const
{
    return this->text;
}

QColor LightButton::getTextColor() const
{
    return this->textColor;
}

QColor LightButton::getAlarmColor() const
{
    return this->alarmColor;
}

QColor LightButton::getNormalColor() const
{
    return this->normalColor;
}

QColor LightButton::getBorderOutColorStart() const
{
    return this->borderOutColorStart;
}

QColor LightButton::getBorderOutColorEnd() const
{
    return this->borderOutColorEnd;
}

QColor LightButton::getBorderInColorStart() const
{
    return this->borderInColorStart;
}

QColor LightButton::getBorderInColorEnd() const
{
    return this->borderInColorEnd;
}

QColor LightButton::getBgColor() const
{
    return this->bgColor;
}

bool LightButton::getCanMove() const
{
    return this->canMove;
}

bool LightButton::getShowRect() const
{
    return this->showRect;
}

bool LightButton::getShowOverlay() const
{
    return this->showOverlay;
}

QColor LightButton::getOverlayColor() const
{
    return this->overlayColor;
}

QSize LightButton::sizeHint() const
{
    return QSize(100, 100);
}

QSize LightButton::minimumSizeHint() const
{
    return QSize(10, 10);
}

void LightButton::setText(const QString &text)
{
    if (this->text != text) {
        this->text = text;
        update();
    }
}

void LightButton::setTextColor(const QColor &textColor)
{
    if (this->textColor != textColor) {
        this->textColor = textColor;
        update();
    }
}

void LightButton::setAlarmColor(const QColor &alarmColor)
{
    if (this->alarmColor != alarmColor) {
        this->alarmColor = alarmColor;
        update();
    }
}

void LightButton::setNormalColor(const QColor &normalColor)
{
    if (this->normalColor != normalColor) {
        this->normalColor = normalColor;
        update();
    }
}

void LightButton::setBorderOutColorStart(const QColor &borderOutColorStart)
{
    if (this->borderOutColorStart != borderOutColorStart) {
        this->borderOutColorStart = borderOutColorStart;
        update();
    }
}

void LightButton::setBorderOutColorEnd(const QColor &borderOutColorEnd)
{
    if (this->borderOutColorEnd != borderOutColorEnd) {
        this->borderOutColorEnd = borderOutColorEnd;
        update();
    }
}

void LightButton::setBorderInColorStart(const QColor &borderInColorStart)
{
    if (this->borderInColorStart != borderInColorStart) {
        this->borderInColorStart = borderInColorStart;
        update();
    }
}

void LightButton::setBorderInColorEnd(const QColor &borderInColorEnd)
{
    if (this->borderInColorEnd != borderInColorEnd) {
        this->borderInColorEnd = borderInColorEnd;
        update();
    }
}

void LightButton::setBgColor(const QColor &bgColor)
{
    if (this->bgColor != bgColor) {
        this->bgColor = bgColor;
        update();
    }
}

void LightButton::setCanMove(bool canMove)
{
    if (this->canMove != canMove) {
        this->canMove = canMove;
        update();
    }
}

void LightButton::setShowRect(bool showRect)
{
    if (this->showRect != showRect) {
        this->showRect = showRect;
        update();
    }
}

void LightButton::setShowOverlay(bool showOverlay)
{
    if (this->showOverlay != showOverlay) {
        this->showOverlay = showOverlay;
        update();
    }
}

void LightButton::setOverlayColor(const QColor &overlayColor)
{
    if (this->overlayColor != overlayColor) {
        this->overlayColor = overlayColor;
        update();
    }
}

void LightButton::setGreen()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(0, 166, 0));
}

void LightButton::setRed()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(255, 0, 0));
}

void LightButton::setYellow()
{
    textColor = QColor(25, 50, 7);
    setBgColor(QColor(238, 238, 0));
}

void LightButton::setBlack()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(10, 10, 10));
}

void LightButton::setGray()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(129, 129, 129));
}

void LightButton::setBlue()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(0, 0, 166));
}

void LightButton::setLightBlue()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(100, 184, 255));
}

void LightButton::setLightRed()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(255, 107, 107));
}

void LightButton::setLightGreen()
{
    textColor = QColor(255, 255, 255);
    setBgColor(QColor(24, 189, 155));
}

void LightButton::startAlarm()
{
    if (!timerAlarm->isActive()) {
        timerAlarm->start();
    }
}

void LightButton::stopAlarm()
{
    if (timerAlarm->isActive()) {
        timerAlarm->stop();
    }
}

void LightButton::alarm()
{
    static bool isAlarm = false;
    if (isAlarm) {
        textColor = QColor(255, 255, 255);
        bgColor = normalColor;
    } else {
        textColor = QColor(255, 255, 255);
        bgColor = alarmColor;        
    }

    this->update();
    isAlarm = !isAlarm;
}

           

六、控件介紹

  1. 超過149個精美控件,涵蓋了各種儀表盤、進度條、進度球、指南針、曲線圖、标尺、溫度計、導覽列、導航欄,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、學習方法、寫作技巧、熱門技術、職場發展等内容,幹貨多多,福利多多!

繼續閱讀