问题
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