gpt4 book ai didi

Qt 获取适合固定 QRect 的大 QString 的子字符串

转载 作者:行者123 更新时间:2023-12-02 19:35:07 25 4
gpt4 key购买 nike

我有一个大字符串,一个固定字体和一个固定矩形来绘制该字符串。

  • 如果字符串不适合,我想知道适合该矩形的子字符串的长度
  • 如果字符串确实适合,那么我想知道边界矩形的高度

我在网上搜索了一整天,但一无所获。

最佳答案

使用QFontMetrics类及其boundingRect类,获取提供的字符串使用的矩形

// assumes myFont has been instantiated
QFontMetrics fm(myFont);
QRect bounds = fm.boundingRect("Some text here");

将边界大小与测试字符串是否适合的区域进行比较。

If the string doesn't fit, I would like to know the length of substring that does fit into that rectangle

如果从boundingRect返回的矩形的边界太大,则递归地删除字符,直到宽度适合您的目标矩形。

bool bFits = false;
QString str = "String to test boundary";
QFontMetrics fm(myFont);
QRect bounds;
do
{
bounds = fm.boundingRect(str);
// Assume testBoundary is the defined QRect of the area to hold the text
if(!testBoundary.contains(bounds) && (!str.isEmpty()) )
str.chop(1);
else
bFits = true;
}while(!bFits);

if the string does fit, then I would like to know bounding rectangle height

这只是调用boundingRect返回的矩形的高度。

int height = bounds.height();

关于Qt 获取适合固定 QRect 的大 QString 的子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34023929/

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