Qt文本過長時,縮減文本並顯示省略號

函數原型:

QString QFontMetrics::elidedText(const QString &text, Qt::TextElideMode mode, int width, int flags = 0) const

第二個參數爲文本縮略後,省略號所在的位置,可選:

Qt::ElideLeft	0	The ellipsis should appear at the beginning of the text.
Qt::ElideRight	1	The ellipsis should appear at the end of the text.
Qt::ElideMiddle	2	The ellipsis should appear in the middle of the text.
Qt::ElideNone	3	Ellipsis should NOT appear in the text.

1、基本使用

//要顯示的超長字符串 
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);

假設ui.label的寬度小於當前字體下strDes的長度,則顯示爲這是一個...

2、封裝成函數

QString ElideText(QFont font,int width,QString strInfo) 
{
	QFontMetrics fontMetrics(font); 
	//如果當前字體下,字符串長度大於指定寬度
	if(fontMetrics.width(strInfo) > width) 
	{
		strInfo= QFontMetrics(font).elidedText(strInfo, Qt::ElideRight, width); 
	} 
	return strInfo; 
}
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章