2017-05-31 102 views
0

我嘗試和看似簡單的東西失敗:定義一個簡單的文本格式化組件內聯,然後用不同的文本多次實例化它。代碼如下如何定義QML組件並重寫屬性?

Item { 
. 
. 
. 
Component { 
    id: favButtonLabelText 
    Text { 
     text: "Blah!" 
     color: StyleSingleton.xNavPrimaryText 
     font.family: StyleSingleton.xNavTextFont 
     font.pointSize: 28 
    } 
} 
. 
. 
.  
Loader { sourceComponent: favButtonLabelText; text: "Diameter" } 

在Loader行處,text屬性無效。試圖在組件上定義一個屬性或別名會被拒絕,「組件對象不能聲明新的屬性」。

我在文檔中找到的唯一示例顯示重寫在內聯組件中定義的Rectanglex屬性。在我看來,重寫Text元素的text屬性是類似的。

我該怎麼做?

回答

3

由於Loader自身設置爲它加載該組件的上下文對象,你可以在它定義一個屬性,並在加載Item使用它。
但是,您必須使用未被您的項目使用的屬性名稱,否則它將被您的項目自己的屬性遮蔽,並且沒有簡單的方法顯式地訪問上下文屬性。

Component { 
    id: favButtonLabelText 
    Text { 
     text: foobar 
    } 
} 
Loader { 
    sourceComponent: favButtonLabelText 
    property string foobar: "Diameter" 
} 
2

由於GrecKo已經說過,可以使用具有其他名稱,如在他的例子foobarLoader的自定義屬性。

如果你不這樣做的加載Item,也可以使用相同名稱的任何花哨的重排根,並與parent.property

Component { 
    id: textComponent 
    Text { 
     // Use "parent" to reference the property of the parent, 
     // which is by default the Loader 
     text: parent.text 
    } 
} 

Column { 
    Repeater { 
     model: ['hallo welt', 'hello world', 'Bonjour monde', '你好世界'] 
     delegate: Loader { 
      property string text: modelData 
      sourceComponent: textComponent 
     } 
    } 
} 
引用它