Unsolved changing QML variables from c++
-
hello,
as I have in QML File:
property bool dbOnline onDbOnlineChanged: { console.log("variable changed"); }
and then somehow from C++ i wish to change this variable so the change will be noticed by QML and will debug the "variable changed"
can you show an example how to do that please?
-
-
@mrjj hello,
yes I have checked those, however they are object properties,
i dont know how to implement this fo common QML variable :( -
@shokarta
Im not sure you can as all sample i have seen is been via what shown in those links/docs.
But Im not super QML expert so give it some days and see if you get
a solution. -
BUMP,
noone know if this is realy possible?
Why should not be realy... -
@shokarta said in changing QML variables from c++:
noone know if this is realy possible?
May be possible, but I don't see use case for this.
The "Qt way" would be to have a C++ QObject which hold the "shared" variable and which will be exposed to QML.
Doing this from QML side is not a good practice in my eyes.Please read this https://doc.qt.io/qt-5/qtqml-cppintegration-overview.html.
This could help you to do things in the best way.
And never forget this fundamental rule: if you fighting against the Qt/QML framework, then you are probably doing things in the wrong way.juste my 2 cts
-
@shokarta
Basically what you are trying to accomplish is having variable on the QML side that will be a state of something else (that is probably kept on the C++ side). You are introducing another variable that needs to be synchronized, and its only purpose is to cache something that should be available on the C++ side.Imagine you have QObject of class DBConnector that is exposed to a QML and this object have bool property called online. Now on the QML side you can simply do
Connections { target: App.Context.dbConnector onOnlineChanged: { console.log("variable changed") } }
App.Context is in this case just a simple class with bunch of properties/objects that are accessible in the QML by:
import Application 1.0 as App
It can be registered using
qmlRegisterSingletonType
on the C++ side
https://doc.qt.io/qt-5/qqmlengine.html#qmlRegisterSingletonType-1
For Qt < 5.14 you have to use static method or free function instead of lambda.You can also use
QQmlContext::setContextPropery
but it is encouraged to use much safer alternatives.EDIT:
I have no knowledge aboutQQmlContext::setContextPropery
been marked as deprecated (I oversimplified some news I have heard). Only thing I know for sure is that there are much safer ways of achieving the same results that will be encouraged in the current and next releases. -
hi
@Jarek-B said in changing QML variables from c++:Connections {
target: App.Context.dbConnector
onOnlineChanged: {
console.log("variable changed")
}
}if you use Qt 5.15 Connections syntax has changed
Connections { target: App.Context.dbConnector function onOnlineChanged() { console.log("variable changed") } }