I just want to change the background color of QML buttons but it seems there are no simple way. Can you tell me a simple way to change the background color of QML Button? Thanks!
Update: a code I have searched:
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
}
}
The common way for QtQuick.Controls 2
is to redefine default Control
visual properties to customize a Control
. The disadvantage of this approach as I said above is that you cannot change, for example, just background color. Overriding Control.background
forcing you to redefine all the element, including border, colors, animation etc.
Looking at the Button
's source we can see that defines default Control.background
property based on a Control.palette. Using this property we can override the Control
properties:
For example:
Button {
text: "Test button"
palette {
button: "green"
}
}
But you should understand that internal source could be changed in the future. Also you have to imagine for yourself what palette properties is used by specified Control.
In the example above I redefine palette for specified Control. But you can redefine the palette globally, either be setting the color in qtquickcontrols2.conf or by setting custom palette in C++ - QGuiApplication::setPalette().