您是否必须完全替换属性值才能对其进行自定义?

问题描述

我不知道如何自定义组件。大多数显示如何自定义替换组件的 background 的示例。例如:

menuBar: MenuBar {
...
        background: Rectangle {
            implicitWidth: 40
            implicitHeight: 40
            color: "red"

            Rectangle {
                color: "#21be2b"
                width: parent.width
                height: 1
                anchors.bottom: parent.bottom
            }
        }
}

为什么我不能做类似下面的事情,因为当我查看 MenuBar.qml 的源代码时,它已经将 Rectangle 用于 background。我宁愿修改现有的 background 而不是从头开始完全重新创建它。

menuBar: MenuBar {
...
   background.color: "red";
}

解决方法

如果您的唯一目标是避免更换背景,您可以使用以下解决方案:

MenuBar {
    id: menuBar1

    Binding {
        target: menuBar1
        property: "color"
        value: "red"
    }
}

但我想你不会喜欢它,因为它很快就会变得非常冗长。 您可能最好编写自己的 MenuBar 实现:

//MyMenuBar.qml

MenuBar {

    property alias backgroundColor: theBackground.color

    background: Rectangle {
        id: theBackground
   }
}

此组件将继承标准 MenuBar 的所有属性,以及添加的 backgroundColor 属性。


顺便说一句,有 grouped properties 的概念,但在这种情况下不起作用,因为 background 被声明为 QQuickItem

,

另一种选择是我还没有找到很多文档。您可以查看 MenuBar(或您感兴趣的任何其他快速控件)的源代码,并查看它用于背景的 palette 属性。所以这就是我在源代码中看到的:

    background: Rectangle {
        implicitHeight: 40
        color: control.palette.button
    }

因此,如果您只是尝试将 palette.button 设置为其他内容,它应该会更改颜色:

MenuBar {
    palette.button: "red"
}

那只会对颜色有帮助。如果您想更改任何其他属性,最好重新创建整个内容。