天天看點

Qt編寫自定義控件18-魔法小魚

一、前言

上次發了個純painter繪制的老鼠,那個就是qt目錄下的demo,改的,隻是比demo中的老鼠稍微胖一點,估計人到中年都發福吧。這次來一個魔法小魚,這條魚可以變換顔色,尾巴還會搖動,可以設定旋轉的角度以及尾巴擺動的幅度等,原理是參考網上一個安卓大神寫的(繪制原理

https://www.jianshu.com/p/3dd3d1524851

)。

其實在Qt學習過程中,如果越到問題找不到相關文章和答案,可以試着将關鍵字改成安卓試試,你會發現另外一篇天地,大量的資源和文章介紹等,就比如安卓中用的java的painter,就幾乎和Qt中的一樣,估計填寫程式設計語言都很類似,連方法名字幾乎都是一樣,設定參數,具有很多通用性,作為一名程式員,最重要的是了解思路和原理,甚至學習的方法,這些掌握了,任何語言都不是問題。

二、實作的功能

  • 1:可設定魚頭+魚身+魚鳍+魚尾的顔色
  • 2:可設定魚頭+魚身+魚鳍+魚尾的比例
  • 3:可設定基準顔色,作為所有統一顔色
  • 4:可設定魚鳍是否擺動
  • 5:可設定魚的停留位置旋轉角度

三、效果圖

Qt編寫自定義控件18-魔法小魚

四、頭檔案代碼

#ifndef MAGICFISH_H
#define MAGICFISH_H

/**
 * 魔幻魚控件 作者:feiyangqingyun(QQ:517216493) 2018-7-15
 * 本控件來源于網絡(原作者:tyroneli(http://www.qtcn.org/bbs/read-htm-tid-65412.html))
 * 繪制原理 https://www.jianshu.com/p/3dd3d1524851
 * 1:可設定魚頭+魚身+魚鳍+魚尾的顔色
 * 2:可設定魚頭+魚身+魚鳍+魚尾的比例
 * 3:可設定基準顔色,作為所有統一顔色
 * 4:可設定魚鳍是否擺動
 * 5:可設定魚的停留位置旋轉角度
 */

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

{
    Q_OBJECT
    Q_PROPERTY(QColor headColor READ getHeadColor WRITE setHeadColor)
    Q_PROPERTY(QColor bodyColor READ getBodyColor WRITE setBodyColor)
    Q_PROPERTY(QColor finColor READ getFinColor WRITE setFinColor)
    Q_PROPERTY(QColor tailColor READ getTailColor WRITE setTailColor)
    Q_PROPERTY(QColor baseColor READ getBaseColor WRITE setBaseColor)

    Q_PROPERTY(bool finMove READ getFinMove WRITE setFinMove)
    Q_PROPERTY(int speed READ getSpeed WRITE setSpeed)
    Q_PROPERTY(double wave READ getWave WRITE setWave)
    Q_PROPERTY(double currentAngle READ getCurrentAngle WRITE setCurrentAngle)

public:
    explicit MagicFish(QWidget *parent = 0);
    ~MagicFish();

protected:
    void resizeEvent(QResizeEvent *);
    void paintEvent(QPaintEvent *);
    void drawHead(QPainter *painter);
    void drawBody(QPainter *painter, const QPointF &pos, double angle);
    void drawFin(QPainter *painter, const QPointF &pos, bool left, double angle);
    void drawTail(QPainter *painter, const QPointF &pos, double angle);
    void drawTail1(QPainter *painter, const QPointF &pos, double angle);
    void drawTail2(QPainter *painter, const QPointF &pos, double angle);

private:
    //計算坐标點
    QPointF calcPoint(const QPointF &pos, double len, double angle);
    double qDegreesToRadians(double degrees);
    double qRadiansToDegrees(double radians);

private:
    QColor headColor;           //魚頭顔色
    QColor bodyColor;           //魚身顔色
    QColor finColor;            //魚鳍顔色
    QColor tailColor;           //魚尾顔色
    QColor baseColor;           //基準顔色

    bool finMove;               //魚鳍是否擺動
    int speed;                  //遊動的速度即尾巴擺動的頻率
    double wave;                //晃動的幅度
    double currentAngle;        //旋轉的角度
    int currentValue;           //遊動的位置

    double headLen;             //魚頭尺寸
    double bodyLen;             //魚身尺寸
    double finLen;              //魚鳍尺寸
    double tailLen;             //魚尾尺寸

    QPointF headPos;            //魚頭坐标
    QTimer *timer;              //定時器處理遊動

public:
    QColor getHeadColor()       const;
    QColor getBodyColor()       const;
    QColor getFinColor()        const;
    QColor getTailColor()       const;
    QColor getBaseColor()       const;

    bool getFinMove()           const;
    int getSpeed()              const;
    double getWave()            const;
    double getCurrentAngle()    const;

    double getHeadLen()         const;
    QPointF getHeadPos()        const;

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

private slots:
    void updateValue();

public slots:
    //設定魚頭顔色
    void setHeadColor(const QColor &headColor);
    //設定魚身顔色
    void setBodyColor(const QColor &bodyColor);
    //設定魚鳍顔色
    void setFinColor(const QColor &finColor);
    //設定魚尾顔色
    void setTailColor(const QColor &tailColor);
    //設定基準顔色
    void setBaseColor(const QColor &baseColor);

    //設定魚鳍是否擺動
    void setFinMove(bool finMove);
    //設定遊動的速度
    void setSpeed(int speed);
    //設定滑動的幅度
    void setWave(double wave);

    //設定目前旋轉的角度
    void setCurrentAngle(double currentAngle);
    void setCurrentAngle(int currentAngle);

    //設定頭部的長度
    void setHeadLen(int headLen);
};

#endif // MAGICFISH_H

           

四、完整代碼

#pragma execution_character_set("utf-8")

#include "magicfish.h"
#include "qpainter.h"
#include "qmath.h"
#include "qtimer.h"
#include "qdebug.h"

MagicFish::MagicFish(QWidget *parent) : QWidget(parent)
{
    headColor = QColor(244, 92, 71, 200);
    bodyColor = QColor(244, 92, 71, 220);
    finColor = QColor(244, 92, 71, 150);
    tailColor = QColor(244, 92, 71, 180);
    baseColor = QColor(244, 92, 71);

    finMove = false;
    speed = 30;
    wave = 1.0;

    currentAngle = 0.0;
    currentValue = 0;

    headLen = 10;
    finLen = headLen * 1.8;
    bodyLen = headLen * 5.2;
    tailLen = headLen * 0.8;

    timer = new QTimer(this);
    connect(timer, SIGNAL(timeout()), this, SLOT(updateValue()));
    timer->start(100);
}

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

void MagicFish::resizeEvent(QResizeEvent *)
{
    headLen = qMin(width(), height()) / 10.0;
    bodyLen = headLen * 5.2;
    finLen = headLen * 1.8;
    tailLen = headLen * 0.8;
}

void MagicFish::paintEvent(QPaintEvent *)
{
    //繪制準備工作,啟用反鋸齒
    QPainter painter(this);
    painter.setRenderHint(QPainter::Antialiasing);

    QPointF middlePos = QPointF(width() / 2, height() / 2);
    headPos = calcPoint(middlePos, bodyLen / 1.5, currentAngle);
    double angle = currentAngle + qSin(qDegreesToRadians(currentValue * 1.2 * wave)) * 2;
    QPointF pos = calcPoint(headPos, bodyLen, angle - 180);

    //繪制頭部
    drawHead(&painter);

    //繪制魚身
    drawBody(&painter, pos, angle);

    //繪制左側魚鳍
    QPointF leftPos = calcPoint(headPos, headLen * 0.9, angle + 110);
    drawFin(&painter, leftPos, true, angle);

    //繪制右側魚鳍
    QPointF rightPos = calcPoint(headPos, headLen * 0.9, angle - 110);
    drawFin(&painter, rightPos, false, angle);

    //繪制魚尾
    drawTail(&painter, pos, angle);
}

void MagicFish::drawHead(QPainter *painter)
{
    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(headColor);
    //魚頭關節圓
    painter->drawEllipse(headPos, headLen, headLen);
    painter->restore();
}

void MagicFish::drawBody(QPainter *painter, const QPointF &pos, double angle)
{
    //計算身體部分四個點
    QPointF pos1 = calcPoint(headPos, headLen, angle - 80);
    QPointF pos2 = calcPoint(pos, headLen * 0.8, angle - 90);
    QPointF pos3 = calcPoint(pos, headLen * 0.8, angle + 90);
    QPointF pos4 = calcPoint(headPos, headLen, angle + 80);

    QPointF leftPos = calcPoint(headPos, bodyLen * 0.56, angle - 130);
    QPointF rightPos = calcPoint(headPos, bodyLen * 0.56, angle + 130);

    //計算繪制路徑
    QPainterPath path;
    path.moveTo(pos1);
    path.quadTo(leftPos, pos2);
    path.lineTo(pos3);
    path.quadTo(rightPos, pos4);
    path.lineTo(pos1);

    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(bodyColor);
    painter->drawPath(path);
    painter->restore();
}

void MagicFish::drawFin(QPainter *painter, const QPointF &pos, bool left, double angle)
{
    double controlAngle = 115;
    double finAngle = finMove ? qSin(qDegreesToRadians(currentValue * 16.1 * wave)) * 12.0 : 2;
    QPointF endPos = calcPoint(pos, finLen, left ? angle + finAngle + 180 : angle - finAngle - 180);
    QPointF controlPos = calcPoint(pos, finLen * 1.8, left ? angle + controlAngle + finAngle : angle - controlAngle - finAngle);

    //計算魚鳍的路徑
    QPainterPath path;
    path.moveTo(pos);
    path.quadTo(controlPos, endPos);
    path.lineTo(pos);

    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(finColor);
    painter->drawPath(path);
    painter->restore();
}

void MagicFish::drawTail(QPainter *painter, const QPointF &pos, double angle)
{
    double flag = 0.6;
    double length = tailLen * (flag + 1);
    double tailAngle = angle + qCos(qDegreesToRadians(currentValue * 1.5 * wave)) * 15;

    QPointF endPos = calcPoint(pos, length, tailAngle - 180);
    QPointF pos1 = calcPoint(pos, tailLen, tailAngle - 90);
    QPointF pos2 = calcPoint(endPos, tailLen * flag, tailAngle - 90);
    QPointF pos3 = calcPoint(endPos, tailLen * flag, tailAngle + 90);
    QPointF pos4 = calcPoint(pos, tailLen, tailAngle + 90);

    QPainterPath path;
    path.moveTo(pos1);
    path.lineTo(pos2);
    path.lineTo(pos3);
    path.lineTo(pos4);

    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(tailColor);
    //魚尾關節大圓
    painter->drawEllipse(pos, tailLen, tailLen);
    //魚尾關節小圓
    painter->drawEllipse(endPos, tailLen * flag, tailLen * flag);
    //魚尾肉部分路徑
    painter->drawPath(path);
    painter->restore();

    //繪制魚尾關節
    drawTail1(painter, endPos, tailAngle);
}

void MagicFish::drawTail1(QPainter *painter, const QPointF &pos, double angle)
{
    double len = tailLen * 0.6;
    double flag = 0.4;
    double length = len * (flag + 2.7);
    double tailAngle = angle + qSin(qDegreesToRadians(currentValue * 1.7 * wave)) * 35;

    QPointF endPos = calcPoint(pos, length, tailAngle - 180);
    QPointF pos1 = calcPoint(pos, len, tailAngle - 90);
    QPointF pos2 = calcPoint(endPos, len * flag, tailAngle - 90);
    QPointF pos3 = calcPoint(endPos, len * flag, tailAngle + 90);
    QPointF pos4 = calcPoint(pos, len, tailAngle + 90);

    QPainterPath path;
    path.moveTo(pos1);
    path.lineTo(pos2);
    path.lineTo(pos3);
    path.lineTo(pos4);

    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(tailColor);
    painter->drawPath(path);
    painter->restore();

    //繪制魚尾魚鳍
    drawTail2(painter, pos, tailAngle);
}

void MagicFish::drawTail2(QPainter *painter, const QPointF &pos, double angle)
{
    double len = tailLen * 0.6;
    double flag = 0.4;
    double length = len * (flag + 2.7);
    double tailWidth = qAbs(qSin(qDegreesToRadians(currentValue * 1.9 * wave)) * len + headLen / 5.0 * 3.0);
    QPointF endPos1 = calcPoint(pos, length, angle - 180);
    QPointF endPos2 = calcPoint(pos, length - 10, angle - 180);

    QPointF pos1 = calcPoint(endPos1, tailWidth, angle - 90);
    QPointF pos2 = calcPoint(endPos1, tailWidth, angle + 90);
    QPointF pos3 = calcPoint(endPos2, tailWidth - headLen / 1.5, angle - 90);
    QPointF pos4 = calcPoint(endPos2, tailWidth - headLen / 1.5, angle + 90);

    QPainterPath path1;
    path1.moveTo(pos);
    path1.lineTo(pos3);
    path1.lineTo(pos4);
    path1.lineTo(pos);

    QPainterPath path2;
    path2.moveTo(pos);
    path2.lineTo(pos1);
    path2.lineTo(pos2);
    path2.lineTo(pos);

    painter->save();
    painter->setPen(Qt::NoPen);
    painter->setBrush(tailColor);
    painter->drawPath(path1);
    painter->drawPath(path2);
    painter->restore();
}

QPointF MagicFish::calcPoint(const QPointF &pos, double len, double angle)
{
    double x = qCos(qDegreesToRadians(angle)) * len;
    double y = qSin(qDegreesToRadians(angle - 180)) * len;
    return QPointF(pos + QPointF(x, y));
}

double MagicFish::qDegreesToRadians(double degrees)
{
    return degrees * double(M_PI / 180);
}

double MagicFish::qRadiansToDegrees(double radians)
{
    return radians * double(180 / M_PI);
}

void MagicFish::updateValue()
{
    //值會一直遞增,需要判斷是否越界
    if (currentValue >= (INT_MAX - speed)) {
        currentValue = 0;
    }

    currentValue = (currentValue + speed) % 54000;
    update();
}

QColor MagicFish::getHeadColor() const
{
    return this->headColor;
}

QColor MagicFish::getBodyColor() const
{
    return this->bodyColor;
}

QColor MagicFish::getFinColor() const
{
    return this->finColor;
}

QColor MagicFish::getTailColor() const
{
    return this->tailColor;
}

QColor MagicFish::getBaseColor() const
{
    return this->baseColor;
}

bool MagicFish::getFinMove() const
{
    return this->finMove;
}

int MagicFish::getSpeed() const
{
    return this->speed;
}

double MagicFish::getWave() const
{
    return this->wave;
}

double MagicFish::getCurrentAngle() const
{
    return this->currentAngle;
}

double MagicFish::getHeadLen() const
{
    return this->headLen;
}

QPointF MagicFish::getHeadPos() const
{
    return this->headPos;
}

QSize MagicFish::sizeHint() const
{
    return QSize(200, 200);
}

QSize MagicFish::minimumSizeHint() const
{
    return QSize(20, 20);
}

void MagicFish::setHeadColor(const QColor &headColor)
{
    if (this->headColor != headColor) {
        this->headColor = headColor;
        update();
    }
}

void MagicFish::setBodyColor(const QColor &bodyColor)
{
    if (this->bodyColor != bodyColor) {
        this->bodyColor = bodyColor;
        update();
    }
}

void MagicFish::setFinColor(const QColor &finColor)
{
    if (this->finColor != finColor) {
        this->finColor = finColor;
        update();
    }
}

void MagicFish::setTailColor(const QColor &tailColor)
{
    if (this->tailColor != tailColor) {
        this->tailColor = tailColor;
        update();
    }
}

void MagicFish::setBaseColor(const QColor &baseColor)
{
    if (this->baseColor != baseColor) {
        this->baseColor = baseColor;

        //根據基準顔色設定其他顔色
        this->baseColor.setAlpha(200);
        headColor = this->baseColor;
        this->baseColor.setAlpha(220);
        bodyColor = this->baseColor;
        this->baseColor.setAlpha(150);
        finColor = this->baseColor;
        this->baseColor.setAlpha(180);
        tailColor = this->baseColor;

        update();
    }
}

void MagicFish::setFinMove(bool finMove)
{
    if (this->finMove != finMove) {
        this->finMove = finMove;
        update();
    }
}

void MagicFish::setSpeed(int speed)
{
    if (this->speed != speed) {
        this->speed = speed;
        update();
    }
}

void MagicFish::setWave(double wave)
{
    if (this->wave != wave) {
        this->wave = wave;
        update();
    }
}

void MagicFish::setCurrentAngle(double currentAngle)
{
    if (this->currentAngle != currentAngle) {
        this->currentAngle = currentAngle;
        update();
    }
}

void MagicFish::setCurrentAngle(int currentAngle)
{
    setCurrentAngle((double)currentAngle);
}

void MagicFish::setHeadLen(int headLen)
{
    if (this->headLen != headLen) {
        this->headLen = headLen;
        this->finLen = headLen * 1.8;
        this->bodyLen = headLen * 5.2;
        this->tailLen = headLen * 0.8;
        update();
    }
}

           

六、控件介紹

  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、學習方法、寫作技巧、熱門技術、職場發展等内容,幹貨多多,福利多多!

繼續閱讀