How to create a custom QML element from a file in C ++?

I have a custom QML element that I use in my application.

MyImageView.qml

I can instantiate this in javascript without problems using ComponentDefinition, for example (names and methods simplified for readability):

attachedObjects: [
    ComponentDefinition {
        id: defMyImageView
        MyImageView { }
    }
]

function addCustom() {
    var obj = defMyImageView.createObject();
    obj.customSource = "xyz";
    myContainer.add(obj);
}

How can I do the same with C ++ while saving the current MyImageView.qml file?

+3
source share
1 answer

I found out after repeated search and experimentation;)

void ArticleParser::addImage(QString imageUrl, QString title) {
    QmlDocument *document = QmlDocument::create(
            "asset:///Articles/ArticleImage.qml"); //load qml file
    document->setParent(rootContainer); 

    if (!document->hasErrors()) {
        //Create Imageview
        Control *control = document->createRootObject<Control>();
        control->setProperty("source", imageUrl); //custom property
        control->setProperty("caption", title); //custom property

        rootContainer->add(control); //add control to my main container
    }
}

The above method is called from within C ++ to add images using my custom image control (which supports http-url), so it can be added dynamically.

+1
source

All Articles