2
votes

I try to add some QML object to my QGraphcisScene but they don't display in the scene. Here is the code.

QList<QObject*> dataList;
dataList.append(new DataObject("Item 1", "red"));
dataList.append(new DataObject("Item 2", "green"));


QDeclarativeEngine engine ;
QDeclarativeContext *context = engine.rootContext();
context->setContextProperty("myModel", QVariant::fromValue(dataList));
QUrl url("qrc:view.qml") ;
QDeclarativeComponent component(&engine,url ) ;
QDeclarativeItem *item = qobject_cast <QDeclarativeItem *>(component.create());
item->setFlag(QGraphicsItem::ItemHasNoContents, false);
myScene->addItem(item);

And here is my qml file:

ListView {
    width: 100; height: 100

    model: myModel
    delegate: Rectangle {
        height: 25
        width: 100
        color: model.modelData.color
        Text { text: name }
    }
}
1
add import QtQuick 1.0 at begging of QML file and check contents of logs (there must be some error report). - Marek R
@MarekR qDebug()<<component.errors() gives () And if I check the myScene->items().size(), it shows that some items are added. - Mike Shaw
@MarekR Btw, can't we use QtQuick2.0 with QgraphicsScene? - Mike Shaw
No! QtQuick 2.0 doesn't use QGraphicsView it has own rendering system (aim was to achieve better hardware support to have better performance). It is even not based on QWidget (QGraphicsView is). - Marek R

1 Answers

3
votes

You can add a QML in a QDeclarativeView to your scene using addWidget:

QDeclarativeView view;
view.setSource( QUrl("qrc:view.qml"));
view.setStyleSheet("background-color:transparent");
QGraphicsProxyWidget * item = myScene->addWidget((QWidget *)view);

For QtQuick 2.0 you can embed QQuickView in a widget using createWindowContainer :

QQuickView *view = new QQuickView();
...

QWidget *container = QWidget::createWindowContainer(view);
container->setMinimumSize(...);
container->setMaximumSize(...);
container->setFocusPolicy(Qt::TabFocus);
QGraphicsProxyWidget * item = myScene->addWidget((QWidget *)container);