我只是想改变QML按钮的背景颜色,但似乎没有简单的方法。你能告诉我一个简单的方法来改变QML按钮的背景颜色吗?谢谢!
更新:我搜索过的代码:
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
}
}
发布于 2018-09-04 14:47:52
QtQuick.Controls 2
的常见方法是重新定义默认的Control
可视属性以自定义Control
。正如我上面所说的,这种方法的缺点是你不能改变,例如,只改变背景颜色。覆盖Control.background
会迫使你重新定义所有元素,包括边框、颜色、动画等。
查看Button
的source,我们可以看到定义了基于Control.palette的默认Control.background
属性。使用此属性,我们可以覆盖Control
属性:
例如:
Button {
text: "Test button"
palette {
button: "green"
}
}
但你应该明白,内部来源可能会在未来发生变化。此外,您还必须自己想象指定的Control使用哪些调色板属性。
在上面的例子中,我为指定的控件重新定义了调色板。但您可以全局重新定义调色板,可以在qtquickcontrols2.conf中设置颜色,也可以在C++ - QGuiApplication::setPalette()中设置自定义调色板。
发布于 2021-03-22 17:23:36
与QT Quick 2配合使用:
Button {
id: button
text: qsTr("Button text")
background: Rectangle {
color: parent.down ? "#bbbbbb" :
(parent.hovered ? "#d6d6d6" : "#f6f6f6")
}
}
上面的代码在按钮按下或悬停时更改按钮颜色。还可以添加边框或其他自定义设置。
发布于 2021-10-28 18:41:12
只需使用Button
的Material.background
就可以做到这一点
Button
{
id: button
Material.background:Material.Red
}
https://stackoverflow.com/questions/52157138
复制相似问题