当前位置:   article > 正文

使用图形视图框架(Graphics View Framework)在QML中创建交互式图形界面_qgraphicsview qml

qgraphicsview qml

使用图形视图框架(Graphics View Framework)在QML中创建交互式图形界面

Graphics View Framework

使用图形视图框架(Graphics View Framework)在QML中创建交互式图形界面

在现代应用程序开发中,图形界面是用户体验的关键。Qt框架为我们提供了一种强大而灵活的方式来创建各种图形界面,而QML(Qt Meta-Object Language)是Qt的一部分,用于设计和构建现代、响应式的用户界面。本文将介绍如何在QML中使用图形视图框架,以创建交互式的图形界面。

什么是图形视图框架(Graphics View Framework)?

图形视图框架是Qt中的一个核心组件,它允许开发者创建和管理2D图形场景。这个框架提供了一个强大的工具集,用于在应用程序中显示和处理图形元素,例如矩形、文本、线条等。它不仅支持静态图形展示,还支持交互和动画效果。

在QML中使用图形视图框架

在QML中使用图形视图框架需要进行一些设置和配置。下面是一些步骤,帮助您在项目中集成图形视图框架:

步骤1:项目配置

首先,确保您的Qt项目已正确配置。在项目的.pro文件中,确保已添加QT += quick widgets,并且设置了正确的Qt版本。还要配置文件的字符集,确保使用UTF-8编码。

步骤2:创建QmlGraphicsView类

在项目中,您需要创建一个自定义的QmlGraphicsView类,该类继承自QQuickPaintedItem,用于在QML中显示图形内容。这个类将充当图形视图的容器。

// QmlGraphicsView.h
#pragma once

// Include necessary Qt headers

class QmlGraphicsView : public QQuickPaintedItem
{
    Q_OBJECT

public:
    QmlGraphicsView(QQuickItem* parent = nullptr)
      : QQuickPaintedItem(parent) {
        // 初始化图形场景并添加图形元素
        // 设置交互选项
    }

    // 实现绘制函数
    void paint(QPainter* painter) override {
        // 绘制图形内容
    }

signals:
    // 自定义信号

private slots:
    // 自定义槽函数

protected:
    // 处理鼠标和交互事件的函数
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
步骤3:注册自定义类型

main.cpp中,使用qmlRegisterType函数将自定义的QmlGraphicsView类注册为QML类型,以便在QML文件中使用。

qmlRegisterType<QmlGraphicsView>("QmlWidgets", 1, 0, "QmlGraphicsView");
  • 1
步骤4:创建QML界面

在QML文件(例如main.qml)中,导入所需的Qt Quick模块和自定义类型,然后创建界面并将自定义的QmlGraphicsView作为子项嵌套在其中。

import QtQuick 2.15
import QtQuick.Window 2.15
import QmlWidgets 1.0

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

    QmlGraphicsView {
        anchors.fill: parent
    }
}
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
步骤5:运行应用程序

最后,在main.cpp中启动应用程序,加载QML界面,并在需要时添加国际化支持。

完整代码
#pragma once

#include <QApplication>
#include <QDebug>
#include <QEvent>
#include <QGraphicsScene>
#include <QGraphicsView>
#include <QQuickPaintedItem>
#include <QQuickWindow>
#include <QPainter>
#include <QGraphicsSceneMouseEvent>

/*#
ref https://het.as.utexas.edu/HET/Software/html/qtdeclarative.html
ref https://doc.qt.io/qt-5/qtquick-porting-qt5.html
ref https://github.com/KDABLabs/DeclarativeWidgets
ref https://www.qt.io/blog/2017/01/19/should-you-be-using-qgraphicsview

https://qmlbook.github.io/#
https://github.com/machinekit/QtQuickVcp
https://github.com/FabriceSalvaire/qt5-vector-graphic-shaders
https://box2d.org/

https://www.learnqt.guide/working-with-events

# 可参考 qtcharts QML 组件,它使用图形视图框架移植到QML图表。
https://github.com/qt/qtcharts/tree/dev

*/
class QmlGraphicsView : public QQuickPaintedItem
{
    Q_OBJECT

public:
    QmlGraphicsView(QQuickItem* parent = nullptr)
      : QQuickPaintedItem(parent) {
        // Set item flags
        setFlag(ItemHasContents, true);

        // Initialize the GraphicsScene
        m_scene = new QGraphicsScene(this);
        setAntialiasing(QQuickItem::antialiasing());
        connect(m_scene, &QGraphicsScene::changed, this, &QmlGraphicsView::sceneChanged);
        connect(this, &QmlGraphicsView::needRender, this, &QmlGraphicsView::renderScene, Qt::QueuedConnection);
        connect(this, SIGNAL(antialiasingChanged(bool)), this, SLOT(handleAntialiasingChanged(bool)));

        // add Text
        m_scene->addText("Hello, world!\ncheungxiongwei");
        m_scene->addRect(1, 1, 85, 32);

        setAcceptedMouseButtons(Qt::AllButtons);
        setAcceptHoverEvents(true);
    }

    ~QmlGraphicsView() { delete m_sceneImage; }

signals:

public:
    void paint(QPainter* painter) override {
        if(m_sceneImage && painter) {
            auto pos = boundingRect().center() - m_scene->sceneRect().center();
            painter->drawImage(pos, *m_sceneImage);
        }
    }

Q_SIGNALS:
    void needRender();
private Q_SLOTS:

    void handleAntialiasingChanged(bool enable) {
        setAntialiasing(enable);
        emit needRender();
    }

    void sceneChanged(QList<QRectF> region) {
        const int count       = region.size();
        const qreal limitSize = 0.01;
        if(count && !m_updatePending) {
            qreal totalSize = 0.0;
            for(int i = 0; i < count; i++) {
                const QRectF& reg = region.at(i);
                totalSize += (reg.height() * reg.width());
                if(totalSize >= limitSize) break;
            }
            // Ignore region updates that change less than small fraction of a pixel,
            // as there is little point regenerating the image in these cases. These
            // are typically cases where OpenGL series are drawn to otherwise static
            // view.
            if(totalSize >= limitSize) {
                m_updatePending = true;
                // Do async render to avoid some unnecessary renders.
                emit needRender();
            } else {
                // We do want to call update to trigger possible gl series updates.
                update();
            }
        }
    }

    void renderScene() {
        m_updatePending = false;

        QSize viewSize = size().toSize();
        if(!m_sceneImage || viewSize != m_sceneImage->size()) {
            delete m_sceneImage;
            qreal dpr    = window() ? window()->devicePixelRatio() : 1.0;
            m_sceneImage = new QImage(viewSize * dpr, QImage::Format_ARGB32);
            m_sceneImage->setDevicePixelRatio(dpr);
            m_sceneImageNeedsClear = true;
        }

        if(m_sceneImageNeedsClear) {
            m_sceneImage->fill(Qt::transparent);
        }

        QPainter painter(m_sceneImage);
        if(antialiasing()) {
            painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
        }
        QRect renderRect(QPoint(0, 0), viewSize);
        m_scene->render(&painter, renderRect, renderRect);
        update();
    }

protected:
    void mousePressEvent(QMouseEvent* event) override {
        m_mousePressScenePoint     = event->pos();
        m_mousePressScreenPoint    = event->globalPos();
        m_lastMouseMoveScenePoint  = m_mousePressScenePoint;
        m_lastMouseMoveScreenPoint = m_mousePressScreenPoint;
        m_mousePressButton         = event->button();
        m_mousePressButtons        = event->buttons();

        QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);
        mouseEvent.setWidget(0);
        mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
        mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
        mouseEvent.setScenePos(m_mousePressScenePoint);
        mouseEvent.setScreenPos(m_mousePressScreenPoint);
        mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
        mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
        mouseEvent.setButtons(m_mousePressButtons);
        mouseEvent.setButton(m_mousePressButton);
        mouseEvent.setModifiers(event->modifiers());
        mouseEvent.setAccepted(false);

        QApplication::sendEvent(m_scene, &mouseEvent);

        update();
    }

    void mouseReleaseEvent(QMouseEvent* event) override {
        QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseRelease);
        mouseEvent.setWidget(0);
        mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
        mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
        mouseEvent.setScenePos(event->pos());
        mouseEvent.setScreenPos(event->globalPos());
        mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
        mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
        mouseEvent.setButtons(event->buttons());
        mouseEvent.setButton(event->button());
        mouseEvent.setModifiers(event->modifiers());
        mouseEvent.setAccepted(false);

        QApplication::sendEvent(m_scene, &mouseEvent);

        m_mousePressButtons = event->buttons();
        m_mousePressButton  = Qt::NoButton;

        update();
    }

    void hoverMoveEvent(QHoverEvent* event) override {
        QPointF previousLastScenePoint = m_lastMouseMoveScenePoint;

        // Convert hover move to mouse move, since we don't seem to get actual mouse move events.
        // QGraphicsScene generates hover events from mouse move events, so we don't need
        // to pass hover events there.
        QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);
        mouseEvent.setWidget(0);
        mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
        mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
        mouseEvent.setScenePos(event->pos());
        // Hover events do not have global pos in them, and the screen position doesn't seem to
        // matter anyway in this use case, so just pass event pos instead of trying to
        // calculate the real screen position.
        mouseEvent.setScreenPos(event->pos());
        mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
        mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
        mouseEvent.setButtons(m_mousePressButtons);
        mouseEvent.setButton(m_mousePressButton);
        mouseEvent.setModifiers(event->modifiers());
        m_lastMouseMoveScenePoint  = mouseEvent.scenePos();
        m_lastMouseMoveScreenPoint = mouseEvent.screenPos();
        mouseEvent.setAccepted(false);

        QApplication::sendEvent(m_scene, &mouseEvent);

        // Update triggers another hover event, so let's not handle successive hovers at same
        // position to avoid infinite loop.
        if(previousLastScenePoint != m_lastMouseMoveScenePoint) {
            update();
        }
    }

    void mouseDoubleClickEvent(QMouseEvent* event) override {
        m_mousePressScenePoint     = event->pos();
        m_mousePressScreenPoint    = event->globalPos();
        m_lastMouseMoveScenePoint  = m_mousePressScenePoint;
        m_lastMouseMoveScreenPoint = m_mousePressScreenPoint;
        m_mousePressButton         = event->button();
        m_mousePressButtons        = event->buttons();

        QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseDoubleClick);
        mouseEvent.setWidget(0);
        mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
        mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
        mouseEvent.setScenePos(m_mousePressScenePoint);
        mouseEvent.setScreenPos(m_mousePressScreenPoint);
        mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
        mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
        mouseEvent.setButtons(m_mousePressButtons);
        mouseEvent.setButton(m_mousePressButton);
        mouseEvent.setModifiers(event->modifiers());
        mouseEvent.setAccepted(false);

        QApplication::sendEvent(m_scene, &mouseEvent);

        update();
    }

private:
    QGraphicsScene* m_scene {nullptr};

    QPointF m_mousePressScenePoint;
    QPoint m_mousePressScreenPoint;
    QPointF m_lastMouseMoveScenePoint;
    QPoint m_lastMouseMoveScreenPoint;
    Qt::MouseButton m_mousePressButton;
    Qt::MouseButtons m_mousePressButtons;

    QImage* m_sceneImage {nullptr};
    bool m_updatePending {false};
    bool m_sceneImageNeedsClear {false};
};
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 14
  • 15
  • 16
  • 17
  • 18
  • 19
  • 20
  • 21
  • 22
  • 23
  • 24
  • 25
  • 26
  • 27
  • 28
  • 29
  • 30
  • 31
  • 32
  • 33
  • 34
  • 35
  • 36
  • 37
  • 38
  • 39
  • 40
  • 41
  • 42
  • 43
  • 44
  • 45
  • 46
  • 47
  • 48
  • 49
  • 50
  • 51
  • 52
  • 53
  • 54
  • 55
  • 56
  • 57
  • 58
  • 59
  • 60
  • 61
  • 62
  • 63
  • 64
  • 65
  • 66
  • 67
  • 68
  • 69
  • 70
  • 71
  • 72
  • 73
  • 74
  • 75
  • 76
  • 77
  • 78
  • 79
  • 80
  • 81
  • 82
  • 83
  • 84
  • 85
  • 86
  • 87
  • 88
  • 89
  • 90
  • 91
  • 92
  • 93
  • 94
  • 95
  • 96
  • 97
  • 98
  • 99
  • 100
  • 101
  • 102
  • 103
  • 104
  • 105
  • 106
  • 107
  • 108
  • 109
  • 110
  • 111
  • 112
  • 113
  • 114
  • 115
  • 116
  • 117
  • 118
  • 119
  • 120
  • 121
  • 122
  • 123
  • 124
  • 125
  • 126
  • 127
  • 128
  • 129
  • 130
  • 131
  • 132
  • 133
  • 134
  • 135
  • 136
  • 137
  • 138
  • 139
  • 140
  • 141
  • 142
  • 143
  • 144
  • 145
  • 146
  • 147
  • 148
  • 149
  • 150
  • 151
  • 152
  • 153
  • 154
  • 155
  • 156
  • 157
  • 158
  • 159
  • 160
  • 161
  • 162
  • 163
  • 164
  • 165
  • 166
  • 167
  • 168
  • 169
  • 170
  • 171
  • 172
  • 173
  • 174
  • 175
  • 176
  • 177
  • 178
  • 179
  • 180
  • 181
  • 182
  • 183
  • 184
  • 185
  • 186
  • 187
  • 188
  • 189
  • 190
  • 191
  • 192
  • 193
  • 194
  • 195
  • 196
  • 197
  • 198
  • 199
  • 200
  • 201
  • 202
  • 203
  • 204
  • 205
  • 206
  • 207
  • 208
  • 209
  • 210
  • 211
  • 212
  • 213
  • 214
  • 215
  • 216
  • 217
  • 218
  • 219
  • 220
  • 221
  • 222
  • 223
  • 224
  • 225
  • 226
  • 227
  • 228
  • 229
  • 230
  • 231
  • 232
  • 233
  • 234
  • 235
  • 236
  • 237
  • 238
  • 239
  • 240
  • 241
  • 242
  • 243
  • 244
  • 245
  • 246
  • 247

代码仓库
https://gitcode.net/cheungxiongwei/qmlwidgets

总结

通过以上步骤,您可以在QML中成功集成图形视图框架,创建交互式的图形界面。这使您能够轻松地管理和展示2D图形元素,为用户提供出色的图形体验。

无论是游戏开发、数据可视化还是其他需要图形界面的应用程序,Qt的图形视图框架为开发者提供了一个强大的工具,使其能够以直观和交互式的方式与用户进行互动。

希望本文对您理解如何在QML中使用图形视图框架提供了一些帮助。如果您想深入学习和探索这个主题,可以查看Qt官方文档和示例代码。祝您在Qt开发中取得成功!

声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/我家小花儿/article/detail/91737
推荐阅读
相关标签
  

闽ICP备14008679号