当前位置:   article > 正文

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

qml graphicsview

使用图形视图框架(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中显示图形内容。这个类将充当图形视图的容器。

  1. // QmlGraphicsView.h
  2. #pragma once
  3. // Include necessary Qt headers
  4. class QmlGraphicsView : public QQuickPaintedItem
  5. {
  6. Q_OBJECT
  7. public:
  8. QmlGraphicsView(QQuickItem* parent = nullptr)
  9. : QQuickPaintedItem(parent) {
  10. // 初始化图形场景并添加图形元素
  11. // 设置交互选项
  12. }
  13. // 实现绘制函数
  14. void paint(QPainter* painter) override {
  15. // 绘制图形内容
  16. }
  17. signals:
  18. // 自定义信号
  19. private slots:
  20. // 自定义槽函数
  21. protected:
  22. // 处理鼠标和交互事件的函数
  23. };

步骤3:注册自定义类型

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

qmlRegisterType<QmlGraphicsView>("QmlWidgets", 1, 0, "QmlGraphicsView");

步骤4:创建QML界面

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

  1. import QtQuick 2.15
  2. import QtQuick.Window 2.15
  3. import QmlWidgets 1.0
  4. Window {
  5. width: 640
  6. height: 480
  7. visible: true
  8. title: qsTr("QmlWidgets")
  9. QmlGraphicsView {
  10. anchors.fill: parent
  11. }
  12. }

步骤5:运行应用程序

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

完整代码

  1. #pragma once
  2. #include <QApplication>
  3. #include <QDebug>
  4. #include <QEvent>
  5. #include <QGraphicsScene>
  6. #include <QGraphicsView>
  7. #include <QQuickPaintedItem>
  8. #include <QQuickWindow>
  9. #include <QPainter>
  10. #include <QGraphicsSceneMouseEvent>
  11. /*#
  12. ref https://het.as.utexas.edu/HET/Software/html/qtdeclarative.html
  13. ref https://doc.qt.io/qt-5/qtquick-porting-qt5.html
  14. ref https://github.com/KDABLabs/DeclarativeWidgets
  15. ref https://www.qt.io/blog/2017/01/19/should-you-be-using-qgraphicsview
  16. https://qmlbook.github.io/#
  17. https://github.com/machinekit/QtQuickVcp
  18. https://github.com/FabriceSalvaire/qt5-vector-graphic-shaders
  19. https://box2d.org/
  20. https://www.learnqt.guide/working-with-events
  21. # 可参考 qtcharts QML 组件,它使用图形视图框架移植到QML图表。
  22. https://github.com/qt/qtcharts/tree/dev
  23. */
  24. class QmlGraphicsView : public QQuickPaintedItem
  25. {
  26. Q_OBJECT
  27. public:
  28. QmlGraphicsView(QQuickItem* parent = nullptr)
  29. : QQuickPaintedItem(parent) {
  30. // Set item flags
  31. setFlag(ItemHasContents, true);
  32. // Initialize the GraphicsScene
  33. m_scene = new QGraphicsScene(this);
  34. setAntialiasing(QQuickItem::antialiasing());
  35. connect(m_scene, &QGraphicsScene::changed, this, &QmlGraphicsView::sceneChanged);
  36. connect(this, &QmlGraphicsView::needRender, this, &QmlGraphicsView::renderScene, Qt::QueuedConnection);
  37. connect(this, SIGNAL(antialiasingChanged(bool)), this, SLOT(handleAntialiasingChanged(bool)));
  38. // add Text
  39. m_scene->addText("Hello, world!\ncheungxiongwei");
  40. m_scene->addRect(1, 1, 85, 32);
  41. setAcceptedMouseButtons(Qt::AllButtons);
  42. setAcceptHoverEvents(true);
  43. }
  44. ~QmlGraphicsView() { delete m_sceneImage; }
  45. signals:
  46. public:
  47. void paint(QPainter* painter) override {
  48. if(m_sceneImage && painter) {
  49. auto pos = boundingRect().center() - m_scene->sceneRect().center();
  50. painter->drawImage(pos, *m_sceneImage);
  51. }
  52. }
  53. Q_SIGNALS:
  54. void needRender();
  55. private Q_SLOTS:
  56. void handleAntialiasingChanged(bool enable) {
  57. setAntialiasing(enable);
  58. emit needRender();
  59. }
  60. void sceneChanged(QList<QRectF> region) {
  61. const int count = region.size();
  62. const qreal limitSize = 0.01;
  63. if(count && !m_updatePending) {
  64. qreal totalSize = 0.0;
  65. for(int i = 0; i < count; i++) {
  66. const QRectF& reg = region.at(i);
  67. totalSize += (reg.height() * reg.width());
  68. if(totalSize >= limitSize) break;
  69. }
  70. // Ignore region updates that change less than small fraction of a pixel,
  71. // as there is little point regenerating the image in these cases. These
  72. // are typically cases where OpenGL series are drawn to otherwise static
  73. // view.
  74. if(totalSize >= limitSize) {
  75. m_updatePending = true;
  76. // Do async render to avoid some unnecessary renders.
  77. emit needRender();
  78. } else {
  79. // We do want to call update to trigger possible gl series updates.
  80. update();
  81. }
  82. }
  83. }
  84. void renderScene() {
  85. m_updatePending = false;
  86. QSize viewSize = size().toSize();
  87. if(!m_sceneImage || viewSize != m_sceneImage->size()) {
  88. delete m_sceneImage;
  89. qreal dpr = window() ? window()->devicePixelRatio() : 1.0;
  90. m_sceneImage = new QImage(viewSize * dpr, QImage::Format_ARGB32);
  91. m_sceneImage->setDevicePixelRatio(dpr);
  92. m_sceneImageNeedsClear = true;
  93. }
  94. if(m_sceneImageNeedsClear) {
  95. m_sceneImage->fill(Qt::transparent);
  96. }
  97. QPainter painter(m_sceneImage);
  98. if(antialiasing()) {
  99. painter.setRenderHints(QPainter::Antialiasing | QPainter::TextAntialiasing | QPainter::SmoothPixmapTransform);
  100. }
  101. QRect renderRect(QPoint(0, 0), viewSize);
  102. m_scene->render(&painter, renderRect, renderRect);
  103. update();
  104. }
  105. protected:
  106. void mousePressEvent(QMouseEvent* event) override {
  107. m_mousePressScenePoint = event->pos();
  108. m_mousePressScreenPoint = event->globalPos();
  109. m_lastMouseMoveScenePoint = m_mousePressScenePoint;
  110. m_lastMouseMoveScreenPoint = m_mousePressScreenPoint;
  111. m_mousePressButton = event->button();
  112. m_mousePressButtons = event->buttons();
  113. QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMousePress);
  114. mouseEvent.setWidget(0);
  115. mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
  116. mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
  117. mouseEvent.setScenePos(m_mousePressScenePoint);
  118. mouseEvent.setScreenPos(m_mousePressScreenPoint);
  119. mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
  120. mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
  121. mouseEvent.setButtons(m_mousePressButtons);
  122. mouseEvent.setButton(m_mousePressButton);
  123. mouseEvent.setModifiers(event->modifiers());
  124. mouseEvent.setAccepted(false);
  125. QApplication::sendEvent(m_scene, &mouseEvent);
  126. update();
  127. }
  128. void mouseReleaseEvent(QMouseEvent* event) override {
  129. QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseRelease);
  130. mouseEvent.setWidget(0);
  131. mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
  132. mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
  133. mouseEvent.setScenePos(event->pos());
  134. mouseEvent.setScreenPos(event->globalPos());
  135. mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
  136. mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
  137. mouseEvent.setButtons(event->buttons());
  138. mouseEvent.setButton(event->button());
  139. mouseEvent.setModifiers(event->modifiers());
  140. mouseEvent.setAccepted(false);
  141. QApplication::sendEvent(m_scene, &mouseEvent);
  142. m_mousePressButtons = event->buttons();
  143. m_mousePressButton = Qt::NoButton;
  144. update();
  145. }
  146. void hoverMoveEvent(QHoverEvent* event) override {
  147. QPointF previousLastScenePoint = m_lastMouseMoveScenePoint;
  148. // Convert hover move to mouse move, since we don't seem to get actual mouse move events.
  149. // QGraphicsScene generates hover events from mouse move events, so we don't need
  150. // to pass hover events there.
  151. QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseMove);
  152. mouseEvent.setWidget(0);
  153. mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
  154. mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
  155. mouseEvent.setScenePos(event->pos());
  156. // Hover events do not have global pos in them, and the screen position doesn't seem to
  157. // matter anyway in this use case, so just pass event pos instead of trying to
  158. // calculate the real screen position.
  159. mouseEvent.setScreenPos(event->pos());
  160. mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
  161. mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
  162. mouseEvent.setButtons(m_mousePressButtons);
  163. mouseEvent.setButton(m_mousePressButton);
  164. mouseEvent.setModifiers(event->modifiers());
  165. m_lastMouseMoveScenePoint = mouseEvent.scenePos();
  166. m_lastMouseMoveScreenPoint = mouseEvent.screenPos();
  167. mouseEvent.setAccepted(false);
  168. QApplication::sendEvent(m_scene, &mouseEvent);
  169. // Update triggers another hover event, so let's not handle successive hovers at same
  170. // position to avoid infinite loop.
  171. if(previousLastScenePoint != m_lastMouseMoveScenePoint) {
  172. update();
  173. }
  174. }
  175. void mouseDoubleClickEvent(QMouseEvent* event) override {
  176. m_mousePressScenePoint = event->pos();
  177. m_mousePressScreenPoint = event->globalPos();
  178. m_lastMouseMoveScenePoint = m_mousePressScenePoint;
  179. m_lastMouseMoveScreenPoint = m_mousePressScreenPoint;
  180. m_mousePressButton = event->button();
  181. m_mousePressButtons = event->buttons();
  182. QGraphicsSceneMouseEvent mouseEvent(QEvent::GraphicsSceneMouseDoubleClick);
  183. mouseEvent.setWidget(0);
  184. mouseEvent.setButtonDownScenePos(m_mousePressButton, m_mousePressScenePoint);
  185. mouseEvent.setButtonDownScreenPos(m_mousePressButton, m_mousePressScreenPoint);
  186. mouseEvent.setScenePos(m_mousePressScenePoint);
  187. mouseEvent.setScreenPos(m_mousePressScreenPoint);
  188. mouseEvent.setLastScenePos(m_lastMouseMoveScenePoint);
  189. mouseEvent.setLastScreenPos(m_lastMouseMoveScreenPoint);
  190. mouseEvent.setButtons(m_mousePressButtons);
  191. mouseEvent.setButton(m_mousePressButton);
  192. mouseEvent.setModifiers(event->modifiers());
  193. mouseEvent.setAccepted(false);
  194. QApplication::sendEvent(m_scene, &mouseEvent);
  195. update();
  196. }
  197. private:
  198. QGraphicsScene* m_scene {nullptr};
  199. QPointF m_mousePressScenePoint;
  200. QPoint m_mousePressScreenPoint;
  201. QPointF m_lastMouseMoveScenePoint;
  202. QPoint m_lastMouseMoveScreenPoint;
  203. Qt::MouseButton m_mousePressButton;
  204. Qt::MouseButtons m_mousePressButtons;
  205. QImage* m_sceneImage {nullptr};
  206. bool m_updatePending {false};
  207. bool m_sceneImageNeedsClear {false};
  208. };

代码仓库

https://gitcode.net/cheungxiongwei/qmlwidgets

总结

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

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

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

本文内容由网友自发贡献,转载请注明出处:【wpsshop博客】
推荐阅读
相关标签
  

闽ICP备14008679号