【问题标题】:How to use QFontMetrics boundingRect to measure size of multilne message?如何使用 QFontMetrics boundingRect 测量多行消息的大小?
【发布时间】:2016-06-07 06:19:08
【问题描述】:

我想实现一个 QGraphicsElement,它在圆角矩形内“按原样”绘制文本。

为了实现QGraphicsElement我需要实现boundedRect函数,所以我需要多行消息的boundedRect。

据我了解,这是我需要使用http://doc.qt.io/qt-4.8/qfontmetrics.html#boundingRect-6 的函数,因为它说它将换行符视为换行符。

现在我的问题是,如果我想知道的信息是文本的boundedRect,那我为什么需要将boundedRect作为参数传递呢?

谁能给我一个如何获取多行 QString 的 boundedRect 的示例?还是我需要手动计算换行符并将其乘以单行高度?

编辑:

正如 arhzu 所示,作为参数传递的 QRect 用于定义多行文本的包含方式。但是,这没有用。因为我希望所述边界框的宽度不使用自动换行。这应该只是最长字符串的宽度。所以,我再次问有没有办法得到这个?或者我应该用换行符分割字符串,然后简单地添加高度并使用找到的最大宽度?

【问题讨论】:

  • 当不使用自动换行标志时,不使用布局约束,返回的边界矩形应该是输入文本的“原样”边界。我也更新了答案以打印出未包装的案例。

标签: qt


【解决方案1】:

QFontMetrics::boundingRectrect 参数限制输入文本的布局。您可以使用Qt::TextWordWrap 标志将长行包装到约束矩形内的多行。这是一个允许的文本宽度变化的示例:

#include <QApplication>
#include <QFontMetrics>
#include <QDebug>

int main(int argc, char *argv[])
{
    QApplication a(argc, argv);
    QFontMetrics fm = a.fontMetrics();

    QString text = QLatin1String("Multiline text string\n"
                                 "containing both long lines and line breaks\n"
                                 "to\n"
                                 "demonstrate bounding rect calculation");

    QList<int> widths = QList<int>() << 100 << 200 << 1000;
    foreach(int width, widths) {
        qDebug() << "With word wrapping:" << fm.boundingRect(QRect(0,0,width,100), Qt::TextWordWrap, text);
    }

    foreach(int width, widths) {
        qDebug() << "No wrapping" << fm.boundingRect(QRect(0,0,width,100), 0, text);
    }

    return 0;
}

在我的系统打印上运行它

With word wrapping: QRect(0,0 87x144)
With word wrapping: QRect(0,0 194x96)
With word wrapping: QRect(0,0 236x64)
No wrapping QRect(0,0 236x64)
No wrapping QRect(0,0 236x64)
No wrapping QRect(0,0 236x64)

编辑:添加了没有自动换行的边界矩形计算。在这种情况下,边界 rect 参数似乎不用于任何事情。

【讨论】:

  • 好的。现在我更好地理解了它,我需要重新提出这个问题。但是非常感谢你,虽然你的答案不是我想要的,但它确实帮助了我。
  • 我已经厌倦了这样做。据我了解,宽度的值也可能在你的第二个中为零。然而,返回边界框的高度使得文本不适合它。但是它确实回答了这个问题,但我仍然选择了手动解决方案。
  • 没问题。如果我添加一个QLabel label; label.setText(text); label.show(); qDebug() &lt;&lt; label.rect();,它会打印与字体度量完全相同的矩形。也许你能提供一些测试数据来看看它是否是 Qt 中的某个错误?
  • 其实系统并没有让我修复我的评论。我工作得很完美。问题是别的东西.. jajaja。谢谢。
猜你喜欢
  • 1970-01-01
  • 2012-05-05
  • 1970-01-01
  • 2020-06-29
  • 1970-01-01
  • 2016-01-23
  • 1970-01-01
  • 2017-07-26
  • 1970-01-01
相关资源
最近更新 更多