How to create custom QML element from file in c++?
-
21-12-2019 - |
Question
I have a custom QML element that I use in my app.
MyImageView.qml
I can create instances of it in javascript without issue using a ComponentDefinition such as (names and methods vastly simplified for sake of readability):
attachedObjects: [
ComponentDefinition {
id: defMyImageView
MyImageView { }
}
]
function addCustom() {
var obj = defMyImageView.createObject();
obj.customSource = "xyz";
myContainer.add(obj);
}
How can I do the same using c++ while keeping the current MyImageView.qml file?
Solution
Figured it out after much searching and experimenting ;)
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 urls) so it can be added dynamically.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow