摘要: 我该如何在文本旁边添加一个图标,而不需要硬编码尺寸,并将它们包在
MouseArea
中…以一种适用于GridLayout
的方式?
我创建了一个QML布局,其中有可点击的“按钮”和标签行。按钮是一个图标和文本:
为了创建按钮,我使用Row
,以便两个项目正确粘在一起(没有任何硬编码的尺寸),并具有GridLayout
可以使用的自动大小:
GridLayout {
columns:2; rowSpacing:30
Text {
text: audioServer.label
Layout.alignment: Qt.AlignLeft
}
Row {
spacing:10; Layout.alignment:Qt.AlignRight
Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
Text { text:"Find Another" }
}
Text {
text: "System uptime "+system.uptime
Layout.alignment: Qt.AlignLeft
}
Row {
spacing:10; Layout.alignment:Qt.AlignRight
Image { width:29; height:30; y:10; source:"qrc:/restart.png" }
Text { text: "Restart" }
}
}
我想在每个按钮周围放置一个MouseArea
。如果我把它放在行内,像这样...
Row {
Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
Text { text:"Find Another" }
MouseArea {
anchors.fill: parent
onClicked: rescan()
}
}
当我在Row
中指定左、右、水平居中、填充或居中锚点时,会出现(合理的)错误:QML Row: Cannot specify left, right, horizontalCenter, fill or centerIn anchors for items inside Row. Row will not function.
更重要的是,布局会被破坏(我认为Row
得到了零宽度,因此GridLayout
使其流到了右侧)。
我无法像这样将MouseArea
移动到GridLayout
之外...
GridLayout {
...
Row {
id: rescanButton
Image { width:29; height:30; y:10; source:"qrc:/rescan.png" }
Text { text:"Find Another" }
}
}
MouseArea {
anchors.fill: rescanButton
onClicked: rescan()
}
因为只能将锚定点设置为兄弟或父级元素。
但我无法将 MouseArea
放在 GridLayout
中,因为它会尝试将其布局为一个项目。
如何获得包装按钮的 MouseArea?
对我来说,使用除 Row
之外的容器是可以接受的,但我强烈不希望硬编码任何文本或容器尺寸。
MouseArea
作为Image
的子元素呢? - Filip HazubskiMouseArea
设为Image
的子元素,但需要将它的width
设置为Image.width + Text.width + gapWidth
。我认为你可以定义Image
和Text
的id
属性,并使其仅在Row
的范围内可用,以便MouseArea
可以使用它们。 - Filip HazubskiMouseArea { width: childrenRect.width; height: childrenRect.height; Row { Image{} Text{} } }
如果您愿意将其发布为答案,我很乐意给您信用。 - Phrogz