在Qt控件中经常遇到文字超出文本框,因此介绍几种换行方式
Qt换行
方式一
QLabel
设置setWordWrap(true);
实现换行。但此方法对于多语言文本不太友好,可以在超出文本框时添加省略符,方法如下
//要显示的超长字符串
QString strDes = "这是一个非常非常非常长的字符串";
QFontMetrics fontMetrics(ui.label->font());
//如果当前字体下,字符串长度大于label宽度
if(fontMetrics.width(strDes) > ui.label->width())
{
strDes = QFontMetrics(ui.label->font()).elidedText(strDes, Qt::ElideRight, ui.label->width());
}
ui.label->setText(strDes);
方法二
以下是官方解释
QTextLayout
It offers many features expected from a modern text layout engine, including Unicode compliant rendering, line breaking and handling of cursor positioning. It can also produce and render device independent layout, something that is important for WYSIWYG applications.
The class has a rather low level API and unless you intend to implement your own text rendering for some specialized widget, you probably won’t need to use it directly.
QTextLayout can be used with both plain and rich text.
QTextLayout
它提供了现代文本布局引擎所期望的许多功能,包括 Unicode 兼容的渲染、换行和光标定位处理。它还可以生成和渲染与设备无关的布局,这对于所见即所得应用程序非常重要。
该类具有相当低级别的 API,除非您打算为某些专用小部件实现自己的文本渲染,否则您可能不需要直接使用它。
QTextLayout 可用于纯文本和富文本。
int leading = fontMetrics.leading();
qreal height = 0;
textLayout.setCacheEnabled(true);
textLayout.beginLayout();
while (1) {
QTextLine line = textLayout.createLine();
if (!line.isValid())
break;
line.setLineWidth(lineWidth);
height += leading;
line.setPosition(QPointF(0, height));
height += line.height();
}
textLayout.endLayout();
// draw
QPainter painter(this);
textLayout.draw(&painter, QPoint(0, 0));