首页 > 解决方案 > 如何禁用 QML 对象的可伸缩性

问题描述

如何禁用 QML 对象的可调整大小?我创建的对象的高度和宽度属性基于可缩放对象,但我不希望在调整父对象大小时调整对象大小。我如何实现这一目标?

 Window {
    id: window
    visible: true
    title: qsTr("Stack")

    Component.onCompleted: {
        window.showMaximized()
    }

    Rectangle {
        width:parent.width/2
        height:parent.height/2
    }
}

使用上面的代码,矩形将创建为父级大小的 1/2,我希望它保持这种状态。当我调整窗口大小时,矩形也会调整大小,我希望它在创建后得到修复。我如何实现这一目标?谢谢你。

标签: qtqml

解决方案


删除您的属性绑定。

Window {
    id: window
    visible: true
    title: qsTr("Stack")

    Component.onCompleted: {
        window.showMaximized()
        rect.width = parent.width / 2;      // use these
        rect.height = parent.height / 2;
    }

    Rectangle {
        id: rect
        // width: parent.width/2    // no property bindings
        // height: parent.height/2
    }
}

rect.width通过在and上使用属性绑定rect.height,您可以使它们受到动态变化的影响。你不想要那个。相反,您可以从 Javascript 调用静态分配。

如果将 JS 代码放在 中Component.onCompleted,它只会运行一次(不会在每次调整窗口大小时更新)。这些分配不会创建属性绑定、修复rect.widthrect.height.


推荐阅读