aviit
aviit

Reputation: 2109

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

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
    }
}

Upvotes: 7

Views: 35107

Answers (3)

mohsen
mohsen

Reputation: 1806

You can do this simply with Material.background of Button:

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

Upvotes: 4

quent
quent

Reputation: 2185

Works with QT Quick 2:

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

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

The above code change the button color when the button is down or hovered. It is also possible to add a border or other customizations.

Upvotes: 14

folibis
folibis

Reputation: 12864

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().

Upvotes: 13

Related Questions