[Solved] Can't dynamically add and display objects to QML from C++ (Qt 5.02)



  • Hi all,

    I've been trying to learn how to dynamically add objects to QML from C++ code, but all the code I write doesn't work.

    I want to add an object defined in Unit.qml to the application's window (defined in generated file main.qml).

    I created a new Qt Quick 2 application (by Create Project --> Applications --> Qt Quick 2 Application (Built-in Elements)), added a method for creating QML objects in class QtQuick2ApplicationViewer (the class was generated by Qt Creator), and called this method from main().

    Then tried to follow "this ":http://qt-project.org/doc/qt-5.0/qtqml/qtqml-cppintegration-interactqmlfromcpp.html article, so the method I added to QtQuick2ApplicationViewer looked like this:

    @void QtQuick2ApplicationViewer::addQmlObject()
    {
    QQmlComponent * component = new QQmlComponent(this->engine(), QUrl::fromLocalFile("Unit.qml"), this);

    QObject * object = component->create();
    

    }@

    Here's Unit.qml code:

    @import QtQuick 2.0

    Item {
    id: unit
    width: 40
    height: 40

    Image {
        id: image
        width: parent.width
        height: parent.height
        anchors.fill: parent
        source: "content/unit.png"
    }
    

    }@

    And it doesn't work. Probably the problem is in my misunderstanding of QML-C++ interacting, but I can't figure out what's wrong.
    Could anyone help me, please?


  • Moderators

    In order to be shown, the object needs to have a parent. Otherwise QML engine does not know where to draw it.

    This is how I do it in CCF:
    @
    // constructor of my hybrid C++/QML item:
    mEffectsComponent = new QQmlComponent(mMainInstance->engine(),
    QUrl::fromLocalFile("qml/effects/Effect.qml"));

    // item creation code, in another function:
    QObject *CcfQmlBaseScenario::createEffect(QObject *parent)
    {
    if (mEffectsComponent->isReady()) {
    QObject *object = mEffectsComponent->create();
    object->set("parent", QVariant::fromValue(parent));
    return object;
    } else {
    return 0;
    }
    }
    @

    It's not exactly the same situation you're having, but maybe the snippet will help you. This is the whole code, if you need it: "link":https://github.com/sierdzio/closecombatfree/blob/master/src/qmlBase/ccfqmlbasescenario.cpp#L30.



  • sierdzio, It works! Thank you sooo much!

    I only had to add the next line to the end of my addQmlObject() method:

    @object->setProperty("parent", QVariant::fromValue(this->rootObject()));@

    The problem is solved.


  • Moderators

    Cool :) Please prepend "[Solved]" to the topic's title (you need to edit your first post too do that), it might help some other bloke in need ;)


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.