Change Image source from c++
-
Hi folks
I found a neat way of altering QML properties from C++, this code sample can change the color property of a rectangle on the fly.
My question is how do you change the source of an image in the same way for the below QML extract.
Adopting the same method doesn't quite work generating run-time errors.C++ QQuickItem* objectimage = quickView->rootObject(); QObject *im = objectimage->findChild<QObject*>("rect"); im->setProperty("color", "red"); QML Image { objectName: "ima" id:pic source: "bgnight.png" Rectangle { objectName: "rect" id:redRect1 width: 100 height: 100 x: 130 y:230 color:"transparent"
-
@celica said in Change Image source from c++:
I found a neat way of altering QML properties from C++, this code sample can change the color property of a rectangle on the fly.
C++ QQuickItem* objectimage = quickView->rootObject(); QObject *im = objectimage->findChild<QObject*>("rect"); im->setProperty("color", "red");
That's not a good practice, pasting some links so I don't paraphrase them:
https://doc.qt.io/qt-5/qtquick-bestpractices.html#interacting-with-qml-from-c
http://doc.qt.io/qt-5/qtqml-cppintegration-overview.html#interacting-with-qml-objects-from-c
https://youtu.be/vzs5VPTf4QQ?t=23m20s -
Let me expand @GrecKo 's links, in case this is what you actually want to do:
https://doc.qt.io/qt-5/qquickimageprovider.html
https://doc.qt.io/qt-5/qtquick-imageprovider-example.html -
You can use this in conjunction with the answer from @GrecKo :
https://doc.qt.io/qt-5/properties.html
You will create a context property accessible from QML and call for it there. Then on your C++ class you will change the Q_PROPERTY variable and emit the signalChanged from there. On QML, get a property hold this value and every change you do to the variable this way, will reflect instantly on QML.