2017-10-06 30 views
1

我在Qt中遇到了一個「設計/實現」問題。 目前我甚至不確定這是否是一個聰明的設計... 這是我的第一篇文章,我不知道從哪裏開始...使用QML中Costum類中的Q_PROPERTY's

所以我會試試這個方法。 .. 目前,我有這樣的事情:

class NewProperty : public QObject 
{ 
    Q_OBJECT 
    Q_PROPERTY(QString name READ name WRITE setName) 
    . 
    . 
    . 

public: 
    NewProperty(const QString &name, QObject *parent = 0); 

    QString name()const; 
    void setName(const QString &name); 
    . 
    . 
    . 
private: 
    QString m_s_name; 
}; 

這是一個「NewProperty」類我想有到底「MyClass的」事業會有比只是一個「名稱」屬性更多。 NewProject.cpp文件目前是非常基本的...

而且項目中還會有幾個MyClass。

我的「MyClass」最後會有幾個「NewProperty」的元素... 但我不確定如何以/ right/nice的方式將「NewProperty」傳遞給QML。 我試圖做這樣的事情:

class QML_EMail : public Base_Output 
{ 
    Q_OBJECT 
public: 
    NewProperty prop1; 
    NewProperty prop2; 
    . 
    . 
    . 
}; 

的main.cpp

... 
qmlRegisterType<NewProperty>  ("NewProperty", 1, 0, "NewProperty"); 
QML_EMail email 
ctx->setContextProperty("email",   QVariant::fromValue(&email)); 
... 

如果我嘗試調用像這樣在QML文件:

import NewProperty 1.0 

Rectangle { 
    id: emailStart 

Component.onCompleted: 
{ 
    console.log(email.prop1.name) 
} 

我只得到這個消息:TypeError:無法讀取未定義的屬性「名稱」

我將不勝感激幫助或爲了更好的編碼提示...

問候,

回答

1

歡迎堆棧溢出。

我不認爲Qt屬性可以這樣使用。如果你想從QML訪問屬性,那麼這個類(基於QObject)的成員必須用Q_PROPERTY自己定義,才能被Qt的元對象系統公開。所以你不能簡單地使用另一個也具有屬性的類。

基本上,你有嵌套的對象的屬性,所以你也必須標記它們,如果你想在QML中使用它們。一個簡單的解決方案是使用會員的關鍵字,如果你不需要getter和setter方法:

Q_PROPERTY(NewProperty prop1 MEMBER prop1) 
NewProperty prop1; 

你仍然可能需要您的自定義NewProperty類暴露元系統,如果你想使用它像一個屬性。有關自定義類型的更多信息,請參閱Creating Custom Qt Types

+0

非常感謝你......你救了我的週末。我完全忽略了文檔中的MEMBER值。很有幫助 – mBucks