如何更改 QML Button Qt Quick Controls 2 的背景颜色?

How to change the background color of a QML Button Qt Quick Controls 2?

我只想改变QML按钮的背景颜色,但似乎没有简单的方法。你能告诉我一个简单的方法来改变 QML Button 的背景颜色吗?谢谢!

更新:我搜索过的代码:

import QtQuick 2.6
import QtQuick.Controls 2.1

Button {
    id: control
    text: qsTr("Button")

    contentItem: Text {
        text: control.text
        font: control.font
        opacity: enabled ? 1.0 : 0.3
        color: control.down ? "#17a81a" : "#21be2b"
        horizontalAlignment: Text.AlignHCenter
        verticalAlignment: Text.AlignVCenter
        elide: Text.ElideRight
    }

    background: Rectangle {
        implicitWidth: 100
        implicitHeight: 40
        opacity: enabled ? 1 : 0.3
        border.color: control.down ? "#17a81a" : "#21be2b"
        border.width: 1
        radius: 2
        color: "black"  // I update background color by this
    }
}

QtQuick.Controls 2 的常用方法是重新定义默认 Control 视觉属性以自定义 Control。正如我上面所说,这种方法的缺点是你不能改变,例如,只是背景颜色。覆盖 Control.background 迫使您重新定义所有元素,包括边框、颜色、动画等。

查看 Buttonsource we can see that defines default Control.background property based on a Control.palette。使用此 属性 我们可以覆盖 Control 属性:

例如:

Button {        
    text: "Test button"
    palette {
        button: "green"
    }
}

但是您应该明白,将来可能会更改内部源。您还必须自己想象指定的控件使用了哪些调色板属性。

在上面的例子中,我为指定的控件重新定义了调色板。但是您可以全局重新定义调色板,或者在 qtquickcontrols2.conf or by setting custom palette in C++ - QGuiApplication::setPalette().

中设置颜色

适用于 QT Quick 2:

Button {
        id: button
        text: qsTr("Button text")

        background: Rectangle {
                color: parent.down ? "#bbbbbb" :
                        (parent.hovered ? "#d6d6d6" : "#f6f6f6")
        }
}

上面的代码在按钮按下或悬停时更改按钮颜色。也可以添加边框或其他自定义设置。

您可以简单地使用 Material.background of Button:

Button 
{
    id: button
    Material.background:Material.Red
}