How to load a QML file into a QGraphicsScene in Qt5

情到浓时终转凉″ 提交于 2019-12-12 00:33:32

问题


I tried to load a qml file into a QGraphicsScene using this code :

QGraphicsScene* scene = new QGraphicsScene;
QQmlEngine *engine = new QQmlEngine;
QQmlComponent component(engine,"main.qml",QQmlComponent::PreferSynchronous);
qDebug()<<component.errors();
QGraphicsObject *object =
 qobject_cast<QGraphicsObject *>(component.create());
scene->addItem(object);

errors() returns nothing and the app output says :

QGraphicsScene::addItem: cannot add null item

回答1:


You can't use QtQuick2 (Qt5's new version of QtQuick/QML) with QGraphicsScene. You need to use it with QQuickView.

If you need to zoom the QML file to make it fit the QQuickView, just use QQuickView::setResizeMode to resize the root object to your view(QQuickView::SizeRootObjectToView).




回答2:


You cannot cast this QObject into a QGraphicsObject. The object instance from QQmlComponent is not a subclass of QGraphicsObject. That's why your cast returns a 0 pointer.



来源:https://stackoverflow.com/questions/18192968/how-to-load-a-qml-file-into-a-qgraphicsscene-in-qt5

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!