gpt4 book ai didi

qml - 为什么添加带有 anchors.fill : parent cause the rows to stack up on one another? 的 MouseArea

转载 作者:行者123 更新时间:2023-12-04 02:21:36 25 4
gpt4 key购买 nike

鉴于此 ListView 工作正常:

ListView {
id: myListView
model: myListModel
anchors.fill: parent

delegate: Row {
id: row
spacing: 5
Text {
text: id
width: 25
horizontalAlignment: Text.AlignHCenter
}

Text {
text: description
}
}
}

为什么添加 MouseAreaanchors.fill: parent 会导致行相互堆叠?如何取回添加 MouseArea 之前的自动垂直间距?我已经尝试将 Row 放入 Rectangle 以及 Component 中。

ListView {
id: myListView
model: myListModel
anchors.fill: parent

delegate: Row {
MouseArea {
anchors.fill: parent
onClicked: myListView.currentIndex = index
}
id: row
spacing: 5

Text {
text: id
width: 25
horizontalAlignment: Text.AlignHCenter
}

Text {
text: description
}
}
}

最佳答案

项目堆叠的原因很简单:它们的高度未设置。委托(delegate)必须始终设置高度。由于您没有指定一个,因此委托(delegate)高度为零,并且封闭文本呈现在相同的 y(零)上,堆叠起来。

然而,这不是这里唯一的问题。您定义了要锚定的 MouseAreaRow 以及 Column 强制对自身内部的项目进行特定排列。添加 anchor 会干扰这种自动机制。还有 docs对此很清楚。你可以阅读那个...

Row is a type that positions its child items along a single row. It can be used as a convenient way to horizontally position a series of items without using anchors.

……还有那个……

[...]since a Row automatically positions its children horizontally, achild item within a Row should not set its x position or horizontallyanchor itself using the left, right, anchors.horizontalCenter, fill orcenterIn anchors.

锚定错误可能会产生不一致的状态,因此 Row 不会像没有锚定项那样从封闭文本继承高度。这反过来会导致零高度和堆叠。

在这种特殊情况下,您可以将 Row 包含在 Item 中,并将填充 MouseArea 应用于后者。生成的代码还正确设置了委托(delegate)高度和宽度,看起来类似于以下内容(请注意,我已经删除了代码中的角色和模型,因为后者在提供的代码片段):

import QtQuick 2.4
import QtQuick.Window 2.2
import QtQuick.Layouts 1.1
import QtQuick.Controls 1.2

ApplicationWindow {
visible: true
width: 200
height: 300

ListView {
id: myListView
model: 20
anchors.fill: parent

delegate: Item {
width: myListView.width
height: text1.height // set the height!
Row {
id: row
anchors.fill: parent
spacing: 5

Text {
id: text1
text: "id"
width: 25
horizontalAlignment: Text.AlignHCenter
}

Text {
text: "description"
}

}
MouseArea { // fills the delegate Item, not the Row!
anchors.fill: parent
onClicked: {
myListView.currentIndex = index
console.info("Area clicked! Index: " + index)
}
}
}
}
}

关于qml - 为什么添加带有 anchors.fill : parent cause the rows to stack up on one another? 的 MouseArea,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28503715/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com