【Qt】文字换行


在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);

方法二

以下是官方解释

QTextLayoutIt 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));

参考文章

  1. Qt 5.15 Qt GUI C++ Classes QTextLayout
  2. QPainter再指定区域内绘制文本并自动换行
  3. Qt 字体(03):QFontMetrics类官翻
  • 5
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值