为什么添加带有anchors.fill的MouseArea:parent导致行相互堆叠?

时间:2015-02-13 16:05:39

标签: qml

鉴于此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
        }
    }
}

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

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
        }
    }
}

1 个答案:

答案 0 :(得分:3)

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

但是,这不是唯一的问题。您定义了要锚定的MouseAreaRow以及Column s强制对其内部的项目进行特定安排。添加锚可能会干扰这种自动机制。 同样docs对此很清楚。你可以读到......

  

Row是一种将子项目沿一行定位的类型。它可以用作水平放置一系列项目而不使用锚点的便捷方式。

......还有......

  

[...] 因为一行自动将其子项水平放置,a   一行中的子项不应设置 x 位置或水平   锚定本身使用,锚点。 horizo​​ntalCenter 填充或   centerIn 锚点。

可能,锚定错误会生成一个不一致的状态,以致Row不会从封闭文本继承高度,因为它没有锚定项目。这反过来导致零高度和堆叠。

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

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)
                }
            }
        }
    }
}