Using a C++ class variable in QML file

◇◆丶佛笑我妖孽 提交于 2021-02-08 03:58:16

问题


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

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!