You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Qt QML中修改QQuickItem的中心并获取其他Item的中心?

解答:Qt QML中修改Item中心及获取其他Item中心的实现

没问题,这两个需求在QML里都能轻松搞定,我给你分情况讲清楚:

一、点击my_item_2时,将my_item_1的中心设置为指定坐标

QML里Item的xy属性对应的是它左上角的位置,所以要让中心对齐到指定点,得先反推左上角的坐标。直接上代码示例:

// 目标Item
Item {
    id: my_item_1
    width: 100
    height: 100
    color: "lightblue"
    // 初始位置
    x: 50
    y: 50
}

// 触发点击的Item
Item {
    id: my_item_2
    width: 60
    height: 60
    color: "orange"
    anchors.bottom: parent.bottom
    anchors.horizontalCenter: parent.horizontalCenter

    MouseArea {
        anchors.fill: parent
        onClicked: {
            // 定义你想要的新中心坐标
            const targetCenter = Qt.point(300, 200);
            // 计算my_item_1左上角的位置,让中心对齐到targetCenter
            my_item_1.x = targetCenter.x - my_item_1.width / 2;
            my_item_1.y = targetCenter.y - my_item_1.height / 2;
        }
    }
}

原理很简单:中心x = 左上角x + 宽度/2,反过来左上角x = 中心x - 宽度/2,y轴同理。

二、获取其他Item的中心并应用到my_item_1

不管是app_main_window还是my_item_2,获取它们的中心都是用同样的逻辑:中心x = 左上角x + 宽度/2中心y = 左上角y + 高度/2

示例1:获取my_item_2的中心并设置给my_item_1

修改上面的onClicked代码就行:

onClicked: {
    // 计算my_item_2的中心坐标
    const item2Center = Qt.point(
        my_item_2.x + my_item_2.width / 2,
        my_item_2.y + my_item_2.height / 2
    );
    // 把my_item_1的中心对齐到my_item_2的中心
    my_item_1.x = item2Center.x - my_item_1.width / 2;
    my_item_1.y = item2Center.y - my_item_1.height / 2;
}

示例2:获取主窗口(app_main_window)的中心

假设主窗口的id是app_main_window,代码如下:

onClicked: {
    // 主窗口的左上角是(0,0),所以中心直接是宽高的一半
    const windowCenter = Qt.point(
        app_main_window.width / 2,
        app_main_window.height / 2
    );
    // 应用到my_item_1
    my_item_1.x = windowCenter.x - my_item_1.width / 2;
    my_item_1.y = windowCenter.y - my_item_1.height / 2;
}

进阶技巧:给Item添加自定义的center属性

如果你经常需要操作中心坐标,可以给Item加一个可读写的center属性,这样代码会更简洁:

Item {
    id: my_item_1
    width: 100
    height: 100
    color: "lightblue"

    // 自定义center属性,自动同步x/y
    property point center: Qt.point(x + width/2, y + height/2)
    onCenterChanged: {
        x = center.x - width/2;
        y = center.y - height/2;
    }
}

之后点击时直接赋值就行,不用再手动计算:

onClicked: {
    // 设置为指定中心
    my_item_1.center = Qt.point(300, 200);
    // 或者设置为my_item_2的中心
    my_item_1.center = Qt.point(my_item_2.x + my_item_2.width/2, my_item_2.y + my_item_2.height/2);
}

内容的提问来源于stack exchange,提问作者TheWaterProgrammer

火山引擎 最新活动