Qml組件化編程7-自繪組件

簡介

本文是《Qml組件化編程》系列文章的第七篇,濤哥會羅列Qt中的所有自繪方案,並提供一些案例和說明。

Qt自帶的組件,外觀都是固定的,一般可以通過qss/Qml style等方式進行定製。

如果要實現外觀特殊的組件,就需要自己繪製了。

注:文章主要發佈在濤哥的博客知乎專欄-濤哥的Qt進階之路

自繪方案

Qt中的自繪方案有這麼一些:

  • QWidget+QPainter / QQuickPaintedItem+QPainter
  • Qml Canvas
  • Qml Shapes
  • QOpenGLWidget / QOpenGLWindow
  • Qml QQuickFrameBufferObject
  • Qml SceneGraph
  • Qml ShaderEffect
  • QVulkanWindow

(GraphicsView和QWidget的繪製類似,就不討論了)

QPainter

QPainter是一個功能強大的畫筆,QWidget中的各種控件如QPushButton、QLable等都是用QPainter畫出來的。

(QWidget的控件在繪製時,還增加了qss樣式表,讓UI定製變得更加方便。)

QWidget+QPainter 示例

QWidget中使用QPainter的方法,是重載paintEvent事件,這裏示例繪製一個進度條:

預覽

//MainWindow.h
#pragma once

#include <QMainWindow>

class MainWindow : public QMainWindow
{
    Q_OBJECT

public:
    MainWindow(QWidget *parent = 0);
    ~MainWindow();
protected:
    void paintEvent(QPaintEvent *event) override;
    void timerEvent(QTimerEvent *event) override;
private:
    QList<QColor> mColorList;
    int mCurrent = 0;
};
//MainWindow.cpp
#include "MainWindow.h"
#include <QPainter>
#include <QtMath>
MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    resize(400, 300);
    mColorList << QColor(51, 52, 54)
               << QColor(75, 85, 86)
               << QColor(87, 103, 103)
               << QColor(95, 119, 121)
               << QColor(101, 132, 134)
               << QColor(104, 146, 145)
               << QColor(104, 158, 158)
               << QColor(101, 169, 168)
               << QColor(92, 182, 180)
               << QColor(79, 194, 191);

    //每秒觸發60次定時器,即刷新率60FPS
    startTimer(1000 / 60);
}

MainWindow::~MainWindow()
{

}
void MainWindow::timerEvent(QTimerEvent *) {
    mCurrent =(mCurrent + 3) % 360;
    update();
}

void MainWindow::paintEvent(QPaintEvent *event)
{
    QPainter painter(this);
    painter.setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing);
    //原點x座標
    qreal a = 100;
    //原點y座標
    qreal b = 100;
    //半徑
    qreal r = 80;
    //每個小圓的半徑遞增值
    qreal roffset = 2;
    //每個小圓的角度遞增值
    qreal angleOffset = 30;

    qreal currentangle = mCurrent ;

    for (int i = 0; i < mColorList.length(); i++) {
        qreal r0 = i * roffset;
        qreal angle = currentangle + i * angleOffset;

        qreal x0 = r * cos(qDegreesToRadians(angle)) + a;
        qreal y0 = r * sin(qDegreesToRadians(angle)) + b;
        painter.setPen(mColorList[i]);
        painter.setBrush(QBrush(mColorList[i]));
        painter.drawEllipse(x0  - r0, y0 - r0, 2 * r0, 2 * r0);
    }
}

QQuickPaintedItem+QPainter 示例

QQuickPaintedItem繼承自QQuickItem,而QQuickItem就是Qml中的Item。

QQuickPaintedItem通過重載paint函數,就可以使用QPainter繪製。

自定義的QQuickPaintedItem子類需要註冊到Qml中才能使用,註冊類型或者註冊實例都可以,具體可以參考《 Qml組件化編程5-Qml與C++交互》

這裏示例QQuickPaintedItem 中使用 QPainter繪製一個陰陽八卦:

預覽

//PBar.h
#pragma once

#include <QQuickPaintedItem>

class PBar : public QQuickPaintedItem
{
    Q_OBJECT
public:
    PBar(QQuickItem *parent = nullptr);

    void paint(QPainter *painter) override;
    void timerEvent(QTimerEvent *event) override;
private:
    QList<QColor> mColorList;
    int mCurrent = 0;
};
//PBar.cpp
#include "PBar.h"
#include <QPainter>
#include <QtMath>
PBar::PBar(QQuickItem *parent) : QQuickPaintedItem (parent)
{
    mColorList << QColor(51, 52, 54)
               << QColor(75, 85, 86)
               << QColor(87, 103, 103)
               << QColor(95, 119, 121)
               << QColor(101, 132, 134)
               << QColor(104, 146, 145)
               << QColor(104, 158, 158)
               << QColor(101, 169, 168)
               << QColor(92, 182, 180)
               << QColor(79, 194, 191);

    //每秒觸發60次定時器,即刷新率60FPS
    startTimer(1000 / 60);
}

void PBar::paint(QPainter *painter)
{
    //原點x座標
    qreal a = 100;
    //原點y座標
    qreal b = 100;
    //半徑
    qreal r = 80;

    qreal r1 = r / 2;
    qreal r2 = r / 6;
    qreal currentangle = mCurrent;


    painter->save();
    painter->setRenderHints(QPainter::Antialiasing|QPainter::TextAntialiasing);
    //red 部分
    {
        painter->setBrush(QBrush(QColor(128, 1, 1)));

        QPainterPath path(QPointF(a + r * cos(qDegreesToRadians( currentangle )), b - r * sin(qDegreesToRadians(currentangle ))));
        path.arcTo(a - r, b - r,
                   r * 2, r * 2,
                   currentangle, 180);
        path.arcTo(a + r1 * cos(qDegreesToRadians(currentangle + 180)) - r1, b - r1 * sin(qDegreesToRadians(currentangle + 180)) - r1,
                   r1 * 2, r1 * 2,
                   currentangle + 180, 180);
        path.arcTo(a + r1*cos(qDegreesToRadians(currentangle)) - r1, b - r1 * sin(qDegreesToRadians(currentangle)) - r1,
                   r1 * 2, r1 * 2,
                   currentangle + 180, -180
                   );

        painter->drawPath(path);
    }

    //blue 部分
    {
        painter->setBrush(QBrush(QColor(1, 1, 128)));
        QPainterPath path(QPointF(a + r * cos(qDegreesToRadians( currentangle )), b - r * sin(qDegreesToRadians(currentangle ))));
        path.arcTo(a - r, b - r,
                   r * 2, r * 2,
                   currentangle, -180);
        path.arcTo(a + r1 * cos(qDegreesToRadians(currentangle + 180)) - r1, b - r1 * sin(qDegreesToRadians(currentangle + 180)) - r1,
                   r1 * 2, r1 * 2,
                   currentangle + 180, 180);
        path.arcTo(a + r1*cos(qDegreesToRadians(currentangle)) - r1, b - r1 * sin(qDegreesToRadians(currentangle)) - r1,
                   r1 * 2, r1 * 2,
                   currentangle + 180, -180
                   );

        painter->drawPath(path);
    }
    {
        // red 小圓
        painter->setBrush(QBrush(QColor(128, 1, 1)));
        QPainterPath path;
        path.addEllipse(a + r1 * cos(qDegreesToRadians(currentangle)) - r2, b - r1 * sin(qDegreesToRadians(currentangle )) - r2,
                        r2 * 2, r2 * 2);
        painter->drawPath(path);
    }
    {
        //blue 小圓
        painter->setBrush(QBrush(QColor(1, 1, 128)));
        QPainterPath path;
        path.addEllipse(a + r1 * cos(qDegreesToRadians(180 + currentangle)) - r2, b - r1 * sin(qDegreesToRadians(180 + currentangle)) - r2,
                        r2 * 2, r2 * 2);
        painter->drawPath(path);
    }
    painter->restore();
}

void PBar::timerEvent(QTimerEvent *event)
{
    (void)event;
    mCurrent =(mCurrent + 3) % 360;
    update();
}

//main.cpp
#include <QGuiApplication>
#include <QQmlApplicationEngine>
#include "PBar.h"
int main(int argc, char *argv[])
{
    QCoreApplication::setAttribute(Qt::AA_EnableHighDpiScaling);

    QGuiApplication app(argc, argv);
    qmlRegisterType<PBar>("PBar", 1, 0, "PBar");
    QQmlApplicationEngine engine;
    const QUrl url(QStringLiteral("qrc:/main.qml"));
    QObject::connect(&engine, &QQmlApplicationEngine::objectCreated,
                     &app, [url](QObject *obj, const QUrl &objUrl) {
                         if (!obj && url == objUrl)
                             QCoreApplication::exit(-1);
                     }, Qt::QueuedConnection);
    engine.load(url);

    return app.exec();
}

//main.qml
import QtQuick 2.0
import QtQuick.Window 2.0
import PBar 1.0
Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello PBar")

    PBar {
        anchors.fill: parent
    }
}

關於QPainter

QPainter底層使用CPU做光柵化渲染,這種方式在沒有GPU的設備中能夠很好地工作。

(我的好友"Qt俠-劉典武"就是這方面的實戰專家,他手上有將近150個精美的自繪組件,比官方還要多,有需要的同學可以聯繫他 QQ517216493)

然而時代在飛速發展,很多設備都帶上了GPU,QPainter在GPU設備上,將不能發揮GPU的全部實力。

(劉典武也在積極跟進GPU繪製)

這裏提一下,有個叫QUItCoding的組織,開發了一套QNanoPainter,接口和QPainter一致,

在大部分場景下都擁有不錯的性能。其底層是基於nanovg的GPU加速。

不過QNanoPainter並沒有合併進Qt官方,具體原因不清楚, 有可能是因爲性能並不是100%達標的。

Qml Canvas

Qml中提供了Canvas組件,接口和html中的Canvas基本一致,可以直接copy html中的Canvas代碼(極少部分不能用)。

當然QPainter實現的功能,也都可以移植到Canvas中。

Canvas渲染性能並不太好,如果有性能要求,還是不要用Canvas了。

這裏示例繪製一個笑臉

預覽

//main.qml
import QtQuick 2.0
import QtQuick.Window 2.0

Window {
    visible: true
    width: 640
    height: 480
    title: qsTr("Hello Canvas")

    Canvas {
        id: canvas
        anchors.fill: parent
        onPaint: {

            var ctx = canvas.getContext('2d');

            ctx.beginPath();
            ctx.arc(75,75,50,0,Math.PI*2,true); // 繪製
            ctx.moveTo(110,75);
            ctx.arc(75,75,35,0,Math.PI,false);   // 口(順時針)
            ctx.moveTo(65,65);
            ctx.arc(60,65,5,0,Math.PI*2,true);  // 左眼
            ctx.moveTo(95,65);
            ctx.arc(90,65,5,0,Math.PI*2,true);  // 右眼
            ctx.stroke();

        }
    }
}

Qml Shapes

Qt5.10開始,Qml增加了Quick.Shapes功能。這是目前官方提供的自繪途徑中,兼顧性能和易用性的最佳選擇。

Shapes底層爲GPU渲染(基於SceneGraph),QPainter能繪製的基礎圖元,都可以用Shapes實現。Shapes再配合上Qml中的

屬性綁定和屬性動畫,可以輕易實現各式各樣的動態、酷炫的UI。

(後續的自定義組件,濤哥將會優先使用Shapes。)

這裏示例實現一個任意圓角的Rectangle組件:

預覽

// TRoundRect.qml
import QtQuick 2.12
import QtQuick.Controls 2.5
import QtQuick.Shapes 1.12
Shape {
    id: root
    //左上角是否圓角
    property bool leftTopRound: true
    //左下角是否圓角
    property bool leftBottomRound: true
    //右上角是否圓角
    property bool rightTopRound: true
    //右下角是否圓角
    property bool rightBottomRound: true
    //圓角半徑
    property real radius
    //顏色
    property color color: "red"

    //多重採樣抗鋸齒
    layer.enabled: true
    layer.samples: 8
    
    //平滑處理
    smooth: true

    //反走樣抗鋸齒
    antialiasing: true

    ShapePath {
        fillColor: color
        startX: leftTopRound ? radius : 0
        startY: 0
        fillRule: ShapePath.WindingFill
        PathLine {
            x: rightTopRound ? root.width - radius : root.width
            y: 0
        }
        PathArc {
            x: root.width
            y: rightTopRound ? radius : 0
            radiusX: rightTopRound ? radius : 0
            radiusY: rightTopRound ? radius : 0
        }

        PathLine {
            x: root.width
            y: rightBottomRound ? root.height - radius : root.height
        }
        PathArc {
            x: rightBottomRound ? root.width - radius : root.width
            y: root.height
            radiusX: rightBottomRound ? radius : 0
            radiusY: rightBottomRound ? radius : 0
        }
        PathLine {
            x: leftBottomRound ? radius : 0
            y: root.height
        }
        PathArc {
            x: 0
            y: leftBottomRound ? root.height - radius : root.height
            radiusX: leftBottomRound ? radius : 0
            radiusY: leftBottomRound ? radius : 0
        }

        PathLine {
            x: 0
            y: leftTopRound ? radius : 0
        }
        PathArc {
            x: leftTopRound ? radius : 0
            y: 0
            radiusX: leftTopRound ? radius : 0
            radiusY: leftTopRound ? radius : 0
        }
    }
}

看一下TRoundRect的用法

import QtQuick 2.0
import QtQuick.Controls 2.5
Rectangle {
    width: 800
    height: 600

    Rectangle { //背景紅色,襯托一下
        x: 10
        width: 100
        height: 160
        color: "red"
    }
    TRoundRect {
        id: roundRect
        x: 40
        y: 10
        width: 200
        height: 160
        radius: 40
        leftTopRound: lt.checked
        rightTopRound: rt.checked
        leftBottomRound: lb.checked
        rightBottomRound: rb.checked
        color: "#A0333666"      //半透明色
    }

    Grid {
        x: 300
        y: 10
        columns: 2
        spacing: 10

        CheckBox {
            id: lt
            text: "LeftTop"
            checked: true
        }
        CheckBox {
            id: rt
            text: "RightTop"
            checked: true
        }
        CheckBox {
            id: lb
            text: "LeftBottom"
            checked: true
        }
        CheckBox {
            id: rb
            text: "rightBottom"
            checked: true
        }
    }
}

QOpenGLWidget / QOpenGLWindow

有的同學學習過OpenGL這類圖形渲染API,Qt爲OpenGL提供了便利的窗口和上下文環境。

QOpenGLWidget用來在QWidget框架中集成OpenGL渲染,QOpenGLWindow用在Qml框架。

使用方法都是子類重載下面三個函數:

void initializeGL();

void paintGL();

void resizeGL(int w, int h);

這裏可以參考官方的示例:

QOpenGLWidget示例

QOpenGLWindow示例

Qt對OpenGL系列的函數都做了封裝,一般使用QOpenGLFunctions就夠了,QOpenGLFunctions是基於OpenGL ES 2.0 API的跨平臺實現,刪減了個別API。

相應的有一個未刪減的OpenGLES2 的封裝:QOpenGLFunctions_ES2。

當然爲了兼容所有OpenGL版本,Qt分別封裝了相應的類

預覽

有特殊版本需要的時候,可以把QOpenGLFunctions換成相應的類。

還有一個OpenGL ES3.0的封裝, QOpenGLExtraFunctions,可以在支持OpenGL ES 3.0的設備上使用。

使用這些functions,一定要在有OpenGL上下文環境的地方,先調用一下initializeOpenGLFunctions。有些版本的init有返回值的,要注意判斷並處理。

Qml SceneGraph

Qml基於GPU實現了一套渲染框架,這個框架就是SceneGraph。

SceneGraph提供了很多GPU渲染相關的功能,以方便進行自繪製,都是以QSG開頭的類,如下圖所示:

預覽

使用方式是在QQuickItem的子類中,重載updatePaintNode函數:

  QSGNode *TaoItem::updatePaintNode(QSGNode *node, UpdatePaintNodeData *)
  {
      QSGSimpleRectNode *n = static_cast<QSGSimpleRectNode *>(node);
      if (!n) {
          n = new QSGSimpleRectNode();
          n->setColor(Qt::red);
      }
      n->setRect(boundingRect());
      return n;
  }

在使用Qml框架的程序中,使用這些QSG功能,將自定義渲染直接加入SceneGraph框架的渲染流程,無疑是性能最優的。

不過問題在於,這些QSG有點難以使用。需要有一定的OpenGL或DirectX相關圖形學知識,並理解SceneGraph的節點交換機制,才能用好。

而懂OpenGL的人,有更好的選擇,就是直接使用OpenGL的API。下面的QQuickFrameBufferObject就是一種途徑。

Qml QQuickFrameBufferObject

QQuickFramebufferObject繼承於QQuickItem(Qml中將它當作一個Item就可以了),用來在一個framebuffer object(FBO)上做渲染,

SceneGraph框架會將這個FBO渲染到屏幕上。

使用的方式是,實現一個QQuickFramebufferObject::Renderer類。

這個類裏面始終是擁有OpenGL上下文環境的,內存也是被SceneGraph框架管理的,只要理解了渲染流程,用起來還是很方便的。

濤哥在Qml中集成 視頻播放器 和 3D模型渲染的時候,就使用了這個FBO。

可以參考這兩個例子:

Qml渲染3D模型

FFmpeg解碼,Qml/OpenGL轉碼渲染

Qml ShaderEffect

學習過圖形學的人,都應該聽說過大名鼎鼎的Shadertoy

只要一點奇妙的Shader代碼,就能渲染出各種酷炫的效果。

Qml中提供了ShaderEffect組件,就可以用來做ShaderToy那樣的特效。

可以參考qyvlik的代碼倉庫:

qyvlik-ShaderToy.qml

以及我很久以前寫的例子:

Tao-ShaderToy

360能量球

Qml中還有個神奇的ShaderEffectSource,可以用在普通Item的layer.effect中,

比如這個例子,就用ShaderEffectSource做了倒影特效:

倒影特效

QVulkanWindow

OpenGL的下一代,已經進化爲vulkan了。

Qt 5.10開始,也提供了vulkan的支持。

濤哥水平有限,這次只提一下,就先不展開說了。

轉載聲明

文章出自濤哥的博客 – 點擊這裏查看濤哥的博客
本作品採用 知識共享署名-非商業性使用-相同方式共享 4.0 國際許可協議進行許可, 轉載請註明出處, 謝謝合作 © 濤哥

聯繫方式


作者 濤哥
開發理念 弘揚魯班文化,傳承工匠精神
博客 https://jaredtao.github.io
知乎 https://www.zhihu.com/people/wentao-jia
郵箱 [email protected]
微信 xsd2410421
QQ 759378563

請放心聯繫我,樂於提供諮詢服務,也可洽談商務合作相關事宜。

打賞


如果覺得濤哥寫的還不錯,還請爲濤哥打個賞,您的讚賞是濤哥持續創作的源泉。


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