“text-overflow” for a QLabel’s text rendering in QT

user1598585 picture user1598585 · Sep 11, 2011 · Viewed 15.2k times · Source

I have got a QLabel element in a widget which can be resized. The text can overflow boundaries, so I need, for the application to look more elegant, some way to make the text generate an ellipsis (...) after the last totally visible word in the text.

Making layouts in HTML/CSS I used to use text-overflow: ellipsis; for this, but for QT classes I have not found any information on this.

Answer

serge_gubenko picture serge_gubenko · Sep 12, 2011

It looks like on your label resize event you can create elided text using the new width of the widget and reset the text. Use QFontMetrics::elidedText method to get the elided version of the string.

QString text("some long text without elipsis");
QFontMetrics metrics(label->font());
QString elidedText = metrics.elidedText(text, Qt::ElideRight, label->width());
label->setText(elidedText);

hope this helps, regards