将qml对象添加到QGraphicsScene

时间:2014-04-23 13:25:29

标签: c++ qt qml qt-quick qgraphicsscene

我尝试将一些QML对象添加到我的QGraphcisScene中,但它们不会在场景中显示。这是代码。

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);

这是我的qml文件:

ListView {
    width: 100; height: 100

    model: myModel
    delegate: Rectangle {
        height: 25
        width: 100
        color: model.modelData.color
        Text { text: name }
    }
}

1 个答案:

答案 0 :(得分:3)

您可以使用addWidget在QDeclarativeView中将QML添加到场景中

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

对于QtQuick 2.0,您可以使用QQuickView在窗口小部件中嵌入createWindowContainer

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

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