2015-09-29 93 views
1

有沒有辦法在QML中訪問C++對象的成員變量?在main.cpp中,我將一個對象暴露給QML。如何在QML中訪問controller.x訪問QML中C++對象的成員變量

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

在控制器:

public: 
int x; 

回答

3

如果你不希望使用屬性綁定,你可以這樣做。

class Controller : public QObject 
{ 
    Q_ObJECT 

    public: 
    Q_INVOKABLE int getX() const { return x; } 

    private: 
    int x; 
} 
在QML

controller.getX() 
+0

好,答覆感謝,這是非常有幫助的,但在我的控制,我有性病:: unordered_map ,ValueReceiver是一類在哪裏有QtcpSocket和那裏我有插槽開始()連接套接字與服務器。我不知道如何從QML連接信號到ValueReceiver。 – Szymson

+0

您可以按照相同的方法。可能是另一個小代碼的問題將會有所幫助。 – ramtheconqueror

+0

在我的課上:Q_INVOKABLE QHash getQHash()const {return valuesReceivers; } 在qml中,我得到:錯誤:未知方法返回類型:QHash Szymson

4

聲明的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