这是我在qt文档上找到的基本示例。在tile
矩形中,我添加了anchors.fill: parent
,并在此下方评论了所有3行,因为我觉得所有这3行都可以被anchors.fill: parent
覆盖。但是一旦我这样做,我就无法拖动元素。
import QtQuick 2.7
import QtQuick.Controls 2.0
import QtQuick.Layouts 1.3
ApplicationWindow {
visible: true
Item {
id: root
width: 64; height: 64
MouseArea {
id: mouseArea
anchors.fill: parent
anchors.centerIn: parent
drag.target: tile
onReleased: parent = tile.Drag.target !== null ? tile.Drag.target : root
Rectangle {
id: tile
anchors.fill: parent
// width: 64; height: 64
// anchors.verticalCenter: parent.verticalCenter
// anchors.horizontalCenter: parent.horizontalCenter
color: "red"
Drag.active: mouseArea.drag.active
Drag.hotSpot.x: 32
Drag.hotSpot.y: 32
states: State {
when: mouseArea.drag.active
ParentChange { target: tile; parent: root }
AnchorChanges { target: tile; anchors.verticalCenter: undefined; anchors.horizontalCenter: undefined }
}
}
}
}
}
为什么填充父矩形会禁用拖放功能?
您将船固定为固定在某物上。如果您想移动它,则需要与您一起折断锚或将其锚定的东西拉动。
这就是锚点的目的 - 将锚定对象固定在其他对象上。如果要使它可移动,则不能锚定。
通过设置:
width: parent.width
height: parent.height
,尽管它的大小相同,但一旦您移动它,显然它将不再填充父母。
现在您可能会说:
"但是,嘿!他们也锚定了对象!"
是的,他们这样做了,但也有行:
states: State {
when: mouseArea.drag.active
ParentChange { target: tile; parent: root }
AnchorChanges { target: tile; anchors.verticalCenter: undefined; anchors.horizontalCenter: undefined }
}
在拖动瓷砖时抬起锚。