gpt4 book ai didi

qt - QML:尝试自动计算字体大小时检测到绑定(bind)循环

转载 作者:行者123 更新时间:2023-12-04 15:58:01 28 4
gpt4 key购买 nike

代码如下:

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;
}
}

我的想法是尝试计算一个字体大小:

一个。始终适合任何具有宽度和尺寸的元素

尽可能大,同时仍然为按钮顶部留出至少 10% 的边距。

我已经测试过了,它运行良好。然而,我不断收到令我担心的警告:

qrc:/main.qml:37:9: QML Button: Binding loop detected for property "font.pixelSize"

这到底是什么意思,我做错了什么?

最佳答案

metrics.font.pixelSize = 0.8*element.height;

这一行是问题,我没有发现文档提到它,但看起来不允许在绑定(bind)期间修改 FontMetrics font 属性。

即使这样也给出了警告。

FontMetrics {
id: metrics
//font.family: "Robotto"
}

function getTextSize(element,text){
metrics.font.family = "Robotto";
return 10
}

我有两个解决方案来删除警告。

解决方案一:

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
}

我的按钮.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;
}
}

关于qt - QML:尝试自动计算字体大小时检测到绑定(bind)循环,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51162423/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com