2016-04-25 198 views
0

我有一個QML Pane與二十多個按鈕,我想在一個地方設置他們的標籤的anchors.horizontalCenteranchors.verticalCentersourceSize.width屬性(屬性?)。這可能嗎?有什麼辦法來設置一些/所有「子」 - 項目的屬性/屬性?

換句話說,我希望做這樣的事情:

Pane { 
    AllButtons: SetThoseProperties { 
     label.sourceSize.width: 32 
     label.anchors.horizontalCenter: parent.horizontalCenter 
     label.anchors.verticalCenter: parent.verticalCenter 
    } 
    Button { 
     id: button1 
     // maybe some reference to the AllButtons thing? 
     label: Image { 
      source: "qrc:/image1.svg" 
     } 
    } 
    Button { 
     id: button1 
     // maybe some reference to the AllButtons thing? 
     label: Image { 
      source: "qrc:/image1.svg" 
     } 
    } 
    // ... 
} 

代替:

Pane { 
    AllButtons: SetThoseProperties { 
     label.sourceSize.width: 32 
     label.anchors.horizontalCenter: parent.horizontalCenter 
     label.anchors.verticalCenter: parent.verticalCenter 
    } 
    Button { 
     id: button1 
     // maybe some reference to the AllButtons thing? 
     label: Image { 
      source: "qrc:/image1.svg" 
      sourceSize.width: 20 
      anchors.horizontalCenter: parent.horizontalCenter 
      anchors.verticalCenter: parent.verticalCenter 
     } 
    } 
    Button { 
     id: button2 
     // maybe some reference to the AllButtons thing? 
     label: Image { 
      source: "qrc:/image2.svg" 
      sourceSize.width: 20 
      anchors.horizontalCenter: parent.horizontalCenter 
      anchors.verticalCenter: parent.verticalCenter 
     } 
    } 
    // ... 
} 

回答

2

創建一個帶有其預定義屬性一起新的QML組件,那麼你可以使用它作爲一個獨立的類型。

您可以輕鬆地通過右鍵單擊現有對象並重構 - >將組件移動到單獨的文件中。

// CustomButton.qml 
Button { 
    property alias image: bImage.source 
    label: Image { 
     id: bImage 
     source: "qrc:/image2.svg" 
     sourceSize.width: 20 
     anchors.horizontalCenter: parent.horizontalCenter 
     anchors.verticalCenter: parent.verticalCenter 
    } 
} 

然後你可以使用它像:

CustomButton { 
    image: "qrc:/image2.svg" 
} 

此外,你可以採取中繼器的優勢:

Column { 
    Repeater { 
     model: 10 
     CustomButton { 
      image: "qrc:/image" + index + ".svg" 
      onClicked: foos[index]() 
     } 
    } 
} 

這會給你的10個按鈕一列,每個圖像源對應於其索引。您可以將每個按鈕的功能分配給一組函數。

使用中繼器,您也可以避免使用額外的CustomButton.qml類型,中繼器會重複其身體中的任何對象,因此您可以爲對象定義屬性一次,這些屬性將應用於所有實例。

如果您指定ListModel,那麼您可以更進一步,除了索引之外,還可以爲每個模型項目設置唯一的自定義屬性。

最後,如果你想輕鬆地覆蓋,而不是引用的屬性值直接使用其他屬性的代理多個對象的屬性,:

// for example in main.qml 
property int imageWidth: 20 

// CustomButton.qml 
... 
sourceSize.width: imageWidth 
... 

這種方式改變imageWidth意志的機會每sourceSize.width它引用它。

相關問題