我希望当我单击或悬停在 GridLayout 中的一行上时更改其背景。 我怎样才能做到这一点?
我尝试为此操作创建一个自定义行,但陷入了这样一个事实:我必须为每个字段(ComboBox、Label、TextInput、Button)创建多个此类对象。
这是我的结果行代码:
Rectangle {
id: root
width: 200
height: 20
color: field.activeFocus ? "#a6a6a6" : (hovered ? "#c0c0c0" : "#eaeaea")
property bool hovered: false
MouseArea {
anchors.fill: parent
hoverEnabled: true
onClicked: {
field.forceActiveFocus()
}
onEntered: { hovered = true}
onExited: { hovered = false}
}
GridLayout {
anchors.fill: parent
columns: 2
Label
{
id: label
Layout.row: 0
Layout.column: 0
text: "Unknown"
Layout.minimumWidth: 80
Layout.fillHeight: true
Layout.fillWidth: true
font.weight: field.activeFocus ? Font.Bold : Font.Normal
}
Label // ComboBox // TextInput // Button
{
id: field
Layout.row: 0
Layout.column: 1
text: "Unknown"
Layout.minimumWidth: 80
Layout.minimumHeight: 20
Layout.fillHeight: true
Layout.fillWidth: true
}
}
}
这里是使用它的地方:
这是解决您问题的一种可能的解决方案。
Item
并允许其通过 focus: true
default property alias children: ctl.children
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Page {
Column {
spacing: 10
Special { Label { text: "Empty" } }
Special { Label { text: "0" } }
Special { Label { text: "0" } }
Special { Label { text: "0" } }
Special { ComboBox { model: ["Empty"] } }
Special { Button { text: "Button" } }
}
}
// Special.qml
import QtQuick
import QtQuick.Controls
import QtQuick.Layouts
Item {
id: control
width: 400
height: 40
focus: true
default property alias children: ctl.children
Rectangle {
anchors.fill: parent
color: control.activeFocus ? "#a6a6a6" : (mouseArea.hovered ? "#c0c0c0" : "#eaeaea")
}
MouseArea {
id: mouseArea
anchors.fill: parent
onClicked: control.forceActiveFocus()
property bool hovered: false
hoverEnabled: true
onEntered: { hovered = true }
onExited: { hovered = false }
}
GridLayout {
anchors.fill: parent
columns: 2
Label
{
Layout.row: 0
Layout.column: 0
text: "Label:"
Layout.minimumWidth: 80
Layout.fillHeight: true
Layout.fillWidth: true
font.weight: control.activeFocus ? Font.Bold : Font.Normal
}
Item // ComboBox // TextInput // Button
{
id: ctl
Layout.row: 0
Layout.column: 1
Layout.minimumWidth: 80
Layout.minimumHeight: 20
Layout.fillHeight: true
Layout.fillWidth: true
}
}
}
您可以在线尝试!