在 QML 文件中使用 C++ 类变量 [英] Using a C++ class variable in QML file

查看:39
本文介绍了在 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"
   ...
}

这篇关于在 QML 文件中使用 C++ 类变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆