gpt4 book ai didi

qt - 调整父级大小时如何更改位置?

转载 作者:行者123 更新时间:2023-12-04 08:38:09 25 4
gpt4 key购买 nike

如何正确更改对象的 x、y,以便在调整父对象的大小时更改其位置?还有,我来介绍一下,如果我将矩形拖到中间,那么当窗口调整大小时,它应该保持在中间。 (仅中间举例,矩形可自由移动)
Example

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
    }
    }
    }
    }
    结果
    该示例产生以下结果:
    原始窗口
    Original window
    调整大小的窗口
    Resized window
    框架被移动
    Moved frame
    窗口再次调整大小
    Moved frame and resized window

    关于qt - 调整父级大小时如何更改位置?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/64697839/

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