How can I use a C++ class variable in QML file in Qt. I want to set a variable based on Q_OS_Android in c++ file and evaluate a condition in QML file. How will this be possible?
You have to declare the variable as property in your header file and register the class with qml in your main. Here is an example for a class Foo and a variable QString var:
class Foo : ...
{
Q_OBJECT
Q_PROPERTY(QString var READ getVar WRITE setVar NOTIFY varChanged)
public:
Foo();
~Foo();
QString getVar() const {return m_var;}
void setVar(const QString &var);
signals:
void varChanged();
public slots:
//slots can be called from QML
private:
QString m_var;
};
In the main you will have something like this:
int main(int argc, char *argv[])
{
QGuiApplication app(argc, argv);
qmlRegisterType<Foo>("MyApp", 1, 0, "Foo");
QQuickView view;
view.setSource(QUrl("qrc:/main.qml"));
view.show();
return app.exec();
}
In your Qml File you can simply import your class using:
import MyApp 1.0
And then use your class as you would any normal QML Type:
Foo{
id: myClass
var: "my c++ var"
...
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With