Qml组件的隐式(implicit)尺寸设置

    科技2024-05-16  88

    介绍

    使用隐式尺寸可以适配组件中的内容,兼容不同长度Qml隐式尺寸属性:implicitHeight : real/ implicitWidth : real若组件没有定义宽高,则该项可以来指定其宽高,隐式尺寸根据内容定义组件的尺寸(默认值是0)。Text和Image不能重写其隐式尺寸。

    使用1-Text组件间接使用

    Text组件内部不支持使用隐式尺寸。

    Item中包含Text,可以根据Text中的内容来动态改变组件的尺寸。程序如下:

    Item { id:root //指定组件的宽高,根据Text的隐式尺寸来确定(12和6是比较合理美观的数值) implicitWidth: text1.implicitWidth+12 implicitHeight: text1.implicitHeight+6 //设置背景色,已进行区分 Rectangle{ anchors.fill: parent color: "lightgreen" radius: 3 } //Text组件 Text { id: text1 text: qsTr("测试11122") //设置文字样式 font.pixelSize: 20 //设置文字居中显示 anchors{ horizontalCenter: parent.horizontalCenter verticalCenter: parent.verticalCenter margins: 5 } } }

    结果如下图,文字居中显示在组件中,组件的尺寸根据文字内容变化

    使用2-Button组件使用

    Button组件的隐式尺寸属性会根据组件中的内容长度变化,默认最小宽=100,最小高=40,程序如下:

    Button{ id:btn1 //默认宽度=100,implicitWidth会根据显示内容的长度自动调整 //默认高度=40,设置24比较美观 implicitHeight: 24 text: "确定111111111111111111111" //设置四边间距 topPadding: 0 bottomPadding: 0 leftPadding: 6 rightPadding:6 //设置背景色 background: Rectangle{ color: "lightgreen" } }

    结果如下:

    Processed: 0.009, SQL: 8