2

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 }
    }
}
Nejat
  • 31,784
  • 12
  • 106
  • 138
Mike Shaw
  • 373
  • 7
  • 22
  • add `import QtQuick 1.0` at begging of QML file and check contents of logs (there must be some error report). – Marek R Apr 23 '14 at 13:45
  • @MarekR qDebug()<items().size(), it shows that some items are added. – Mike Shaw Apr 23 '14 at 13:48
  • @MarekR Btw, can't we use QtQuick2.0 with QgraphicsScene? – Mike Shaw Apr 23 '14 at 14:09
  • 1
    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 Apr 23 '14 at 15:21

1 Answers1

3

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);
Nejat
  • 31,784
  • 12
  • 106
  • 138
  • Thanks for your answer. If I am right, this is a QtQuick 1.0 solution. Is there a QtQuick 2.0 solution. And besides, is this a good idea to implement part of my interface with QML, as I have the main part in QGraphicsView? – Mike Shaw Apr 24 '14 at 07:07
  • Yes it is for QtQuick 1.0. I have updated the answer for QtQuick 2.0. – Nejat Apr 24 '14 at 07:57
  • Tried this but it opens a new window with the QML next to my main window which contains the qgraphicsscene. – Jean-Michaël Celerier Feb 28 '16 at 16:26