c++ - 在QML中访问C++对象的成员变量

标签 c++ qt object qml

有没有办法在 QML 中访问 C++ 对象的成员变量?在 main.cpp 中,我向 QML 公开了一个对象。如何在 QML 中访问 controller.x

Controller ctrl;
QQuickView view;
QQmlContext* ctx = view.rootContext();
ctx->setContextProperty("controller", &ctrl);

在 Controller 中:

public:
 int x;

最佳答案

将 C++ 成员声明为 property :

class Controller : public QObject
{
    Q_OBJECT
    Q_PROPERTY(int x MEMBER x NOTIFY xChanged)

    // ...

signals:
    void xChanged();

private:
    int x;
};

您还需要声明一个信号,这就是 NOTIFY 功能所指的内容。这将使 QML 知道属性值何时更改:

A MEMBER variable association is required if no READ accessor function is specified. This makes the given member variable readable and writable without the need of creating READ and WRITE accessor functions. It's still possible to use READ or WRITE accessor functions in addition to MEMBER variable association (but not both), if you need to control the variable access.

然后像这样在 QML 中访问它:

controller.x

关于c++ - 在QML中访问C++对象的成员变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32847721/

相关文章:

c++ - C++ 中二进制表示的交织 vector

c++ - 在结构中初始化静态 constexpr 变量和类

c++ - QDateedit 鼠标按下时日期改变

javascript - 将函数返回值保存在 const 中是未定义的

python - 将字符串转换为 Python 对象

PHP 和 MySQL OOP - 为什么我没有得到返回结果?

c++ - 空覆盖 C++11

c++ - CEditBox 或 CListBox 哪个更适合大量记录数据

c++ - Qt Windows 获取鼠标光标图标

qt - 具有代码控制属性的组件(无默认值)