问题
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:
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"
...
}
来源:https://stackoverflow.com/questions/28450178/using-a-c-class-variable-in-qml-file