×
Namespaces

Variants
Actions

Archived:QLabel text ellipsis using QFontMetrics approach

From Nokia Developer 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
Symbian
Article
Keywords: QLabel, Ellipsis, Text
Created: gnuton (19 Jun 2011)
Last edited: hamishwillee (11 Oct 2012)

Contents

Overview

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.

TextEllipsis.png

Ellipsis

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) :
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
 
connect(ui->lineEdit, SIGNAL(textChanged(QString)), this, SLOT(updateText(QString)));
}
 
MainWindow::~MainWindow()
{
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);
ui->label->setText(elidedString);
}
~

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.

Conclusion

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.
120 page views in the last 30 days.

Was this page helpful?

Your feedback about this content is important. Let us know what you think.

 

Thank you!

We appreciate your feedback.

×