qlable实现固定宽度自动换行

QLabel实现固定宽度自动换行

超出宽度时自动添加换行符,超出高度时自动获取高度,然后设置QLabel的高度,

QLabel放在一个滚动区域里面,这样可以实现带滚动条的label,
然后QLabel可以设置对齐方式,字体,颜色等参数,
qlineedit等实现对齐方式比较麻烦,

原理:QLabel碰见“\n”时会换行

第一步,对输入的字符串进行处理,添加换行符,然后获取高度,

//自动换行
QString DialogBox::AutoFeed(QString text, int &iHeight)
{
	QString strText = text;

	QFontMetrics fm(m_ui->textEdit->font());
	int width = fm.width(strText);
	int height = fm.height();

	int leadingHeight = fm.leading();
	int lineSpacingHeight = fm.lineSpacing();

	QString strFeed = "";
	int newLine = 0;

	int newLineWidthCount = 0;
	if (!strText.isEmpty())
	{
		QString curChar;
		for (int i = 0; i < strText.length()  ; i++)///
		{
			curChar = strText[i];
			if (curChar == "\n")
			{
				newLine++;
			}

			newLineWidthCount = newLineWidthCount + fm.width(curChar);
			if (newLineWidthCount > 380)
			{
				newLineWidthCount = 0;
				strFeed = strFeed + "\n";
				newLine++;
			}
			strFeed = strFeed + curChar;	
		}		
	}
	iHeight = (height + leadingHeight)* (newLine + 2);
	return strFeed;
}

第二步:设置文本到QLabel,然后设置QLabel的高度

	QString strContent = m_TextContentStr;
	int rows = 0;
	QString FeedStr = AutoFeed(strContent, rows);
	m_ui->textEdit->setText(FeedStr);
	//m_ui->scrollArea的高度125
	if (rows < 120)
	{
		rows = 120;
	}
	
	m_ui->textEdit->setFixedHeight(rows);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值