使用图形视图框架(Graphics View Framework)在QML中创建交互式图形界面
- 使用图形视图框架(Graphics View Framework)在QML中创建交互式图形界面
- 使用图形视图框架(Graphics View Framework)在QML中创建交互式图形界面
- 什么是图形视图框架(Graphics View Framework)?
- 在QML中使用图形视图框架
- 步骤1:项目配置
- 步骤2:创建QmlGraphicsView类
- 步骤3:注册自定义类型
- 步骤4:创建QML界面
- 步骤5:运行应用程序
- 完整代码
- 总结
使用图形视图框架(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:
// 处理鼠标和交互事件的函数
};
步骤3:注册自定义类型
在main.cpp
中,使用qmlRegisterType
函数将自定义的QmlGraphicsView
类注册为QML类型,以便在QML文件中使用。
qmlRegisterType<QmlGraphicsView>("QmlWidgets", 1, 0, "QmlGraphicsView");
步骤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
}
}
步骤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};
};
代码仓库
https://gitcode.net/cheungxiongwei/qmlwidgets
总结
通过以上步骤,您可以在QML中成功集成图形视图框架,创建交互式的图形界面。这使您能够轻松地管理和展示2D图形元素,为用户提供出色的图形体验。
无论是游戏开发、数据可视化还是其他需要图形界面的应用程序,Qt的图形视图框架为开发者提供了一个强大的工具,使其能够以直观和交互式的方式与用户进行互动。
希望本文对您理解如何在QML中使用图形视图框架提供了一些帮助。如果您想深入学习和探索这个主题,可以查看Qt官方文档和示例代码。祝您在Qt开发中取得成功!