代码如下:
import QtQuick 2.10
import QtQuick.Controls 2.1
import QtQuick.Controls.Material 2.1
ApplicationWindow {
id: mainW
visible: true
width: 1000
height: 500
title: qsTr("Hello World")
Column{
anchors.centerIn: parent
spacing: 0.05*parent.height
Button {
id: btn1
font.family: "Robotto"
width: 0.8*mainW.width
height: 0.1*mainW.height
text: "TEXT1"
font.pixelSize: 0.8*height
anchors.horizontalCenter: parent.horizontalCenter
}
Button {
id: btn2
font.family: "Robotto"
width: 0.8*mainW.width
height: 0.1*mainW.height
text: "A"
font.pixelSize: 0.8*height
anchors.horizontalCenter: parent.horizontalCenter
}
Button {
id: btn3
font.family: "Robotto"
width: 0.8*mainW.width
height: 0.2*mainW.height
//text: "A really really, but very really long text with lots of stuff"
text: "Another button"
font.pixelSize: getTextSize(btn3,btn3.text)
anchors.horizontalCenter: parent.horizontalCenter
}
}
FontMetrics {
id: metrics
font.family: "Robotto"
}
function getTextSize(element,text){
metrics.font.pixelSize = 0.8*element.height;
var brect = metrics.boundingRect(text);
if (brect.width > element.width*0.8){
var k = element.width*0.8/brect.width
return Math.floor(metrics.font.pixelSize*k);
}
else return metrics.font.pixelSize;
}
}
我的想法是尝试计算一种字体大小:
a。始终适合宽度和大小的任何元素
b。尽可能大,同时在按钮顶部至少留出10%的利润。
我已经对其进行了测试,并且效果很好。但是,我不断收到警告,令我感到担忧:
qrc:/main.qml:37:9: QML Button: Binding loop detected for property "font.pixelSize"
这到底是什么意思,我在做什么错?
答案 0 :(得分:1)
metrics.font.pixelSize = 0.8*element.height;
这是问题所在,我没有找到文档中提到的内容,但是看起来在绑定期间不允许修改FontMetrics font
属性。
即使这也会发出警告。
FontMetrics {
id: metrics
//font.family: "Robotto"
}
function getTextSize(element,text){
metrics.font.family = "Robotto";
return 10
}
我有两种解决方案来消除警告。
解决方案1:
Button {
id: btn3
font.family: "Robotto"
width: 0.8*mainW.width
height: 0.2*mainW.height
//text: "A really really, but very really long text with lots of stuff"
text: "Another button"
//font.pixelSize: getTextSize(btn3,btn3.text)
Component.onCompleted: {
font.pixelSize = getTextSize(btn3,btn3.text)
}
}
解决方案2:
MyButton {
font.family: "Robotto"
width: 0.8 * mainW.width
height: 0.2 * mainW.height
text: "Another button"
anchors.horizontalCenter: parent.horizontalCenter
}
MyButton.qml
Button {
id: button
font.pixelSize: getTextSize()
readonly property real pWidth: width * 0.8
readonly property real pHeight: height * 0.8
FontMetrics {
id: metrics
font.family: button.font.family
font.pixelSize: button.pHeight
}
function getTextSize(){
var brect = metrics.boundingRect(text);
if (brect.width > pWidth){
var k = pWidth / brect.width
return Math.floor(metrics.font.pixelSize * k);
} else
return metrics.font.pixelSize;
}
}