函数原型:
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());
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
;
}