在 QML 文件中使用 C++ 类变量

2022-01-19 00:00:00 qml c++

如何在 Qt 的 QML 文件中使用 C++ 类变量.我想在 c++ 文件中设置一个基于 Q_OS_Android 的变量并评估 QML 文件中的条件.这怎么可能?

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?

推荐答案

你必须在你的头文件中将变量声明为属性,并在你的 main.xml 中使用 qml 注册该类.下面是一个类 Foo 和一个变量 QString var 的例子:

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;
};

主要是这样的:

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();
}

在您的 Qml 文件中,您可以使用以下方法简单地导入您的类:

In your Qml File you can simply import your class using:

import MyApp 1.0

然后像使用任何普通 QML 类型一样使用您的类:

And then use your class as you would any normal QML Type:

Foo{
   id: myClass
   var: "my c++ var"
   ...
}

相关文章