按钮的属性"样式"无效



为什么每次使用style属性时都会收到此错误:invalid property "style"

Button {
text: "A 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.Button,您可以使用以下内容:

Button {
id: control
text: "A button"
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" }
}
}
}

如果你反复使用这个定义,你可以把它(用text: "A button"(放在一个单独的文件中,你可以调用MyButton.qml,然后你可以使用MyButton { text: "A Button" }

灰色是 qml 中按钮的默认颜色。如果您想设置样式,这是我经常使用的选项。创建按钮的矩形子组件,设置 anchors.fill,然后在矩形上设置颜色。这将是您现在按钮的颜色。

您可以使用矩形、文本和鼠标区域组件来创建按钮。这样,就没有必要的风格。你可以这样做,

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" }
}
Text{
anchors.centerIn: parent
text: qsTr("A button")
}
MouseArea{
id: control
anchors.fill: parent
onClicked: {
//Your Button Function
}
}
}

最新更新