2016-01-06 55 views
1

假設我有這樣如何把附加屬性到子項

RowLayout { 
    MyItem { 
     Layout.fillWidth: true 
     Layout.fillHeight: true 
     ... // other properties 
    } 
    MyItem { 
     Layout.fillWidth: true 
     Layout.fillHeight: true 
     ... // other properties 
    } 
} 

的成分在其中MyItem.qml是這樣

Rectangle { 
    ... // other properties 
    // Layout.fillWidth: true 
    // Layout.fillHeight: true 
} 

我可以把Layout.fillWidthMyItem定義,讓我不需要重複在RowLayout

回答

1

我可以把Layout.fillWidth放到MyItem,所以我不需要在RowLayout中重複它嗎?

我認爲這個問題有答案:如果你不想重複,只需使用Repeater類型。該文檔指出

由Repeater實例化的項按順序插入爲Repeater的父節點的子節點。插入在中繼器在其父堆疊列表中的位置之後立即開始。這允許在佈局內使用的中繼器爲

以下文檔中的示例使用,但是可以將相同的方法應用於其他佈局,例如, RowLayout。實際上,它適用於根據Repeater性質(「在父項內部插入項目」)附加屬性的任何類型。

下面是一個例子。假設我們已經定義了一個Example類型。

import QtQuick 2.5 

Rectangle { 
    property alias text: inner.text 
    color: "steelblue" 

    Text { 
     id: inner 
     anchors.centerIn: parent 
     font.pixelSize: 30 
    }  
} 

我們可以增加布局屬性我們Example類型Repeater裏面,比如像這樣:

import QtQuick 2.5 
import QtQuick.Window 2.2 
import QtQuick.Layouts 1.1 

Window { 
    id: window 
    width: 600 
    height: 400 
    visible: true 

    RowLayout { 
     id: row 
     anchors.fill: parent 

     Repeater { 
      model: 6    

      delegate : Example { 
       text: index 
       Layout.fillWidth: true // layout options added in the delegate 
       Layout.fillHeight: true 
       Layout.alignment: Qt.AlignCenter 
       Layout.maximumWidth: parent.width/model.length 
      } 
     } 
    } 
} 

Repeatermodel屬性可以是一個字符串數組或另一種模式,照常。

這種方法足夠靈活,可以組合多個Repeater來創建更復雜的結構。例如,請參見以下示例,其中Text用於填充GridLayout中的屏幕:

import QtQuick 2.5 
import QtQuick.Window 2.2 
import QtQuick.Layouts 1.1 

Window { 
    id: window 
    width: 600 
    height: 400 
    visible: true 

    GridLayout { 
     id: grid 
     anchors.fill: parent 
     rows: 2 
     columns: 6 

     Repeater { 
      model: grid.columns 
      Text { 
       Layout.fillWidth: true 
       Layout.fillHeight: true 
       Layout.row: 0 
       Layout.column: index 
       verticalAlignment: Text.AlignVCenter 
       horizontalAlignment: Text.AlignHCenter 
       text: index + 1 // index of the repeater as text 
      } 
     } 

     Repeater { 
      model: grid.columns 
      Text { 
       Layout.fillWidth: true 
       Layout.fillHeight: true 
       Layout.row: 1 
       Layout.column: index 
       verticalAlignment: Text.AlignVCenter 
       horizontalAlignment: Text.AlignHCenter 
       text: index + 7 
      } 
     } 
    } 
} 
0

是的,你可以做到這一點,但每當你決定使用該組件在一個地方有沒有附加屬性命名爲Layout.fillWidth,或者更一般的情況下,只要你不打算使用它,因爲它會在一個錯誤結束佈局中的頂層元素。