Search code examples
qtbuttonqmlqtquickcontrols2

Qml style Button


I have structure for my page and I want add some ButtonStyle for my button (I followed example from documentation), now I have a question, why I can't add style for this button. Below is my page structure

import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
import QtQuick.Controls.Styles 1.4
Page
{
...
header: ToolBar {
    ...
    RowLayout{
        Button {
        ...
        style: ButtonStyle {
            background: Rectangle {
            implicitWidth: 100
            implicitHeight: 25
            border.width: control.activeFocus ? 2 : 1
            border.color: "#888"
            radius: 4
            gradient: Gradient {
                GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
                GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
                }
            }
        }
        }
    }
}
}

Solution

  • You have chosen QtQuick Controls 2 Button (import QtQuick.Controls 2.0), for which styling can be done directly with background (i.e QtQuick.Controls.Styles is not needed) ... Customizing Qt Quick Controls 2. On the other hand if you want to use a QtQuick.Controls 1.x Button then you need to change your import to import QtQuick.Controls 1.4 along with QtQuick.Controls.Styles 1.4 and your styling will work ... Qt Quick Controls Styles.

    With QtQuick Controls 2, you can style Button directly with background like this:

    Button {
        id:control
        background: Rectangle {
            implicitWidth: 100
            implicitHeight: 25
            border.width: control.activeFocus ? 2 : 1
            border.color: "#888"
            radius: 4
            gradient: Gradient {
                GradientStop { position: 0 ; color: control.pressed ? "#ccc" : "#eee" }
                GradientStop { position: 1 ; color: control.pressed ? "#aaa" : "#ccc" }
            }
        }
    }