How can I add elements created in QML to a QGraphicsView ?

In order to add elements created in QML to a QGraphicsView [doc.qt.nokia.com], you can create a QDeclarativeComponent [doc.qt.nokia.com] which loads the QML code and then create an instance of this component using create() [doc.qt.nokia.com]. For example:

  1. QDeclarativeEngine engine;
  2. QDeclarativeComponent component(&engine);
  3. component.setData("import QtQuick 1.0\nText { text: \"Hello world!\" }", QUrl());
  4. QDeclarativeItem *item = qobject_cast<QDeclarativeItem *>(component.create());
  5.  

Since QDeclarativeItem [doc.qt.nokia.com] is a QGraphicsObject [doc.qt.nokia.com] you can add it to your QGraphicsScene [doc.qt.nokia.com].

The following example illustrates how this can be done.

main.cpp

  1. #include <QtGui>
  2. #include <QtDeclarative>
  3.  
  4. int main(int argc, char** argv)
  5. {
  6.         QApplication app(argc, argv);
  7.  
  8.         QDeclarativeEngine engine;
  9.         QDeclarativeComponent component(&engine);
  10.         component.loadUrl(QUrl::fromLocalFile("test.qml"));
  11.         QDeclarativeItem *item = qobject_cast <QDeclarativeItem *>(component.create());
  12.  
  13.         QGraphicsView view;
  14.         QGraphicsScene *scene = new QGraphicsScene(&view);
  15.         view.setScene(scene);
  16.         scene->addItem(item);
  17.         view.show();
  18.         return app.exec();
  19. }

test.qml
  1. import QtQuick 1.0
  2.  
  3.  Rectangle {
  4.      width: 100
  5.      height: 100
  6.      color: "red"
  7.      border.color: "black"
  8.      border.width: 5
  9.      radius: 10
  10.  }

1 comment

January 28, 2013

Picture of David_Gil David_Gil

Lab Rat

Strictly speaking, one adds an item to a QGraphicsScene and views it with a QGraphicsView.

Useful tip, by the way. Thank you.

Write a comment

Sorry, you must be logged in to post a comment.