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 } } }结果如下图,文字居中显示在组件中,组件的尺寸根据文字内容变化
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" } }结果如下: