有没有办法在 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/