Please note that as of October 24, 2014, the Nokia Developer Wiki will no longer be accepting user contributions, including new entries, edits and comments, as we begin transitioning to our new home, in the Windows Phone Development Wiki. We plan to move over the majority of the existing entries. Thanks for all your past and future contributions.

Archived:QLabel text ellipsis using QFontMetrics approach

From Wiki
Jump to: navigation, search

Archived.pngArchived: This article is archived because it is not considered relevant for third-party developers creating commercial solutions today. If you think this article is still relevant, let us know by adding the template {{ReviewForRemovalFromArchive|user=~~~~|write your reason here}}.

Qt Quick should be used for all UI development on mobile devices. The approach described in this article (based on QWidget) is deprecated.

This article shows how to elide QLabels using QFontMetrics::elidedText.

Article Metadata
Tested withCompatibility
Platform(s): Symbian, Maemo
Keywords: QLabel, Ellipsis, Text
Created: gnuton (19 Jun 2011)
Last edited: hamishwillee (11 Oct 2012)



Some Qt widgets such as QLabels are able to display text. If the text doesn't fit inside the widget, the exceeding characters are not displayed making the written text looking bad.

There are several solutions to this problem. Usually if the application runs on desktop, there are some themes which can help to elide the exceeding text removing the latest 3 characters and adding ellipsis ("..."). This unfortunately doesn't happen on Mobile platforms where these Qt styles are missing.



The approach I'm going to explain here makes use of QFontMetrics::ElidedText a method which, as described in the documentation page, returns an elided version of the string passed as argument that is calculated according to a width.

#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent) :
ui(new Ui::MainWindow)
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(updateText(QString)));
delete ui;
void MainWindow::updateText(const QString& string){
QFont f = ui->label->font();
QFontMetrics fm = QFontMetrics(f);
int maxWidth = ui->label->width();
QString elidedString = fm.elidedText(string,Qt::ElideRight, maxWidth);

Other approaches

Another elegant way to solve this problem, that permits to display a nice gradient effect on the latest characters, instead of the "...", is shown in the Danimo's blog.


This is one of the simplest way to ellipse text in Qt. Among several solutions available, I preferred to show this one, not just for its simplicity, but even because it doesn't involve subclassing at all: this permits the developer to use standard QLabel which can be handled in a visual way by using Qt Designer.

This page was last modified on 11 October 2012, at 01:14.
107 page views in the last 30 days.