如何正确更改对象的 x、y,以便在调整父级大小时它会更改其位置?还有,我会介绍一下,如果我将矩形拖到中间,那么当窗口调整大小时,它应该保持在中间。 (中间仅举例,矩形可自由移动)
import QtQuick 2.9
import QtQuick.Window 2.2
import QtQuick.Controls 2.3
Window {
visible: true
width: 640
height: 480
onWidthChanged: {
block.x -= block.previousWidth - width
block.previousWidth = width
}
onHeightChanged: {
block.y -= block.previousHeight - height
block.previousHeight = height
}
Rectangle {
id: block
color: "red"
width: 50
height:50
x: 100
y: 50
property int previousWidth: 0
property int previousHeight:0
Component.onCompleted: {
previousWidth = parent.width
previousHeight = parent.height
}
MouseArea {
anchors.fill: parent
drag.target: block
}
}
}
最佳答案
我必须承认,起初我对这个问题并没有留下深刻的印象。然而,当我思考它时,它代表了一个非常有趣且有效的用例。所以我很乐意提供解决方案。
解决方案
我会这样处理这个问题:
- 使框架成为背景图像的子框架。
- 使用
Item.scale
来缩放图像,而不是手动计算坐标,从而有效地保留框架相对于图像的相对位置。
示例
这是我为您准备的一个示例,用于演示如何实现建议的解决方案:
import QtQuick 2.15
import QtQuick.Window 2.15
Window {
visible: true
width: 640
height: 480
Image {
anchors.centerIn: parent
source: "alphabet.png"
scale: parent.width/sourceSize.width
Rectangle {
id: frame
width: parent.width/7
height: parent.height/4
border.color: "black"
color: "transparent"
antialiasing: true
MouseArea {
anchors.fill: parent
drag.target: parent
}
}
}
}
结果
该示例产生以下结果:
原始窗口
调整窗口大小
框架已移动
窗口再次调整大小
关于qt - 当父级调整大小时如何更改位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64697839/