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?
1 Answer
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"
...
}
4 Comments
Retired Ninja
Your answer is correct, but I'm not sure what "//only slots can be called from QML" is about. Any function can be called from Qml if it is marked Q_INVOKABLE and the parameter and return types are registered with Qml.
luffy
yes you are right. But I find it far simpler to just use slots since they can be called from QML without having to register or mark them! PS: I will remove the "only" from my answer ;)
BaCaRoZzo
You can find it simpler but still
Q_INVOKABLE is important. E.g. you can tag Q_INVOKABLE the methods of a QAbstractListModel-derived class and use them in QML instead of adding "QML-friendly" wrapping method for the methods in the original class. That was one of the main purposes for introducing Q_INVOKABLE.QtRoS
"var" is a quite bad name for property.