我有一個“基礎”組件,它控制專案“childItem”的縱橫比:
//AspectRatio.qml
import QtQuick 2.12
Rectangle
{
property real targetAspectRatio: 16 / 9
color: "black"
anchors.fill: parent
onWidthChanged:
{
var _ratio = parent.width / parent.height
var _width = 0
if(_ratio > targetAspectRatio) //Too wide
{
_width = parent.height * targetAspectRatio
}
else
{
_width = parent.width
}
childItem.width = _width
}
onHeightChanged:
{
var _ratio = parent.width / parent.height
var _height = 0
if(_ratio > targetAspectRatio) //Too wide
{
_height = parent.height
}
else
{
_height = parent.width / targetAspectRatio
}
childItem.height = _height
}
Item
{
id: childItem
anchors.centerIn: parent
}
}
我想將 AspectRatio.qml 用作通用組件并覆寫“childItem”,具體取決于使用組件的背景關系。如何像這樣覆寫“childItem”?
//child.qml
AspectRatio
{
childItem : Rectangle
{
color: "red"
}
}
這種機制也用在標準的 qml 組件中,比如這里。但我不清楚如何實作這一目標。
uj5u.com熱心網友回復:
您的問題有多種解決方案。
您可以創建一個 childItem 屬性并手動將其放入children屬性中,Item
如下所示:
// AspectRatio.qml
Rectangle {
property real targetAspectRatio: 16 / 9
property Item childItem
children: [childItem]
color: "black"
anchors.fill: parent
onWidthChanged: // ...
onHeightChanged: // ...
}
// Usage
AspectRatio {
childItem : Rectangle {
color: "red"
}
}
或者,您可以以另一種方式進行操作,并將 childItem 系結到子項,并且沒有顯式設定器,并且您的屬性只是一個“視圖” children
:
readonly property Item childItem: children[0]
// Usage
AspectRatio {
Rectangle { /* ... */ }
}
為了能夠使用這兩種語法,您可以使用默認屬性,覆寫 Item 的子默認屬性:
default property Item childItem
children: [childItem]
// Usage
AspectRatio {
Rectangle { /* ... */ }
}
// OR
AspectRatio {
childItem: Rectangle { /* ... */ }
}
我會說這是我的首選解決方案。
你沒有問,但我會用宣告性系結替換你在 onWidth/heightChanged 中的命令式代碼(并將錨移到外面):
Rectangle {
id: root
property real targetAspectRatio: 16 / 9
default property Item childItem
children: [childItem]
color: "black"
Binding {
target: root.childItem
property: "width"
value: Math.min(root.height * root.targetAspectRatio, root.width)
}
Binding {
target: root.childItem
property: "height"
value: Math.min(root.width / root.targetAspectRatio, root.height)
}
}
uj5u.com熱心網友回復:
您不能“覆寫”一個專案,但您可以創建一個指向專案的子串列的屬性。這就是background
您在控制元件上提到的屬性之類的作業方式。通過分配給該屬性,您實際上是在插入一個物件作為包含 Item 的任何內容的子項。
//AspectRatio.qml
Rectangle
{
property alias childItem: childContainer.data
Item
{
id: childContainer
anchors.centerIn: parent
}
}
//child.qml
AspectRatio
{
childItem : Rectangle
{
width: 100
height: 100
color: "red"
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/496979.html