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

标签 qt text word-wrap

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

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

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

最佳答案

使用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/

相关文章:

c++ - QT串口发送一个字节

javascript - 用于丢失文本样式的脚注的 Indesign 脚本

具有像素尺寸的 PHP 自动换行

label - 如何在 JfreeChart 中包装类别标签

qt - Qt 中的 Paint() 与 PaintEvent()

c++ - 直通几何着色器

html - 空白属性打破了元素的宽度

css - 为什么 `white-space` 在 IE 和 Firefox 之间不一致?

qt - QPixmap.loadFromData() 不从 QByteArray 加载图像

javascript - ACE Editor : disable syntax validation, 但保持语法突出显示