我想要实现一个QGraphicsElement,它在圆角矩形中绘制文本“原样”。
为了实现QGraphicsElement,我需要实现boundedRect函数,所以我需要多行消息的boundedRect。
据我所知,这是我需要使用http://doc.qt.io/qt-4.8/qfontmetrics.html#boundingRect-6的函数,因为它说它将把换行符当作换行符。
现在我的问题是,如果我想知道的信息是文本的boundedRect,为什么我需要传递boundedRect作为参数呢?
有人能给我举一个例子,说明如何获得多行boundedRect的QString吗?或者,我是否需要手动计算换行符,并按单行高度进行多次计数?
编辑:
正如arhzu所示,作为参数传递的QRect用于定义包含多行文本的方式。然而,这是没有用的。因为我想说的包围框的智慧是这样的,没有字包装被使用。这应该是最长字符串的宽度。那么,我再问一次,到底有没有得到这个?或者我应该将字符串拆分成换行符,然后简单地添加高度并使用找到的最大宽度?
发布于 2016-06-07 08:50:35
rect参数用于QFontMetrics::boundingRect约束输入文本的布局。可以使用Qt::TextWordWrap标志将长行包装为约束rect中的多行。下面是一个允许的文本宽度变化的例子:
#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)编辑:添加边框计算,没有文字包装。看来,在这种情况下,在任何情况下都不使用边界重排论点。
https://stackoverflow.com/questions/37671839
复制相似问题