Qml 样式按钮

Qml style Button

我的页面有结构,我想为我的按钮添加一些 ButtonStyle(我遵循了文档中的示例),现在我有一个问题,为什么我不能添加 style这个按钮。下面是我的页面结构

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

您选择了 QtQuick Controls 2 Button (import QtQuick.Controls 2.0),其样式可以直接使用 background 完成(即不需要 QtQuick.Controls.Styles).. .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.

使用 QtQuick Controls 2,您可以像这样直接使用 background 设置 Button 的样式:

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