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