Hi I am interested in eliding text in a QLabel in the middle of the text in C++. I found the text elide mode property but it looks it only applies to QAbstractItemViews. Also here it says QLabel can elide text that doesn't fit within it, but only in one line but then doesn't say how to do it. Also here it is super easy but it's in QML/Qt Quick. Is there an easy way to do this? Do I have to override the paint event and use QFontMetrics or something like that? I'd imagine this would be as simple as setting a text elide middle property but perhaps I am mistaken. Thanks!
Asked
Active
Viewed 618 times
0
-
From the [Elided Label Example](https://doc.qt.io/qt-6/qtwidgets-widgets-elidedlabel-example.html) (your link): `QString lastLine = content.mid(line.textStart()); QString elidedLastLine = fontMetrics.elidedText(lastLine, Qt::ElideRight, width()); painter.drawText(QPoint(0, y + fontMetrics.ascent()), elidedLastLine);` – Scheff's Cat Sep 12 '22 at 06:57
-
[QFontMetrics::elidedText()](https://doc.qt.io/qt-6/qfontmetrics.html#elidedText) is used to convert the original string into a new one where parts might be replaced by the ellipses. There you can provide the `Qt::TextElideMode`. However, it seems that `QLabel` doesn't support ellipses out of the box. - You have to make your custom label like shown in the linked sample. – Scheff's Cat Sep 12 '22 at 07:00
-
There is nothing native for QLabel yet. This feature has been requested for many years, see [QTBUG-4250](https://bugreports.qt.io/browse/QTBUG-4250). – Pamputt May 22 '23 at 15:11
1 Answers
0
Here's the code thanks to Scheff's Cat.
//elidedlabel.h
#ifndef ELIDEDLABEL_H
#define ELIDEDLABEL_H
#include <QLabel>
#include <QPainter>
class ElidedLabel : public QLabel
{
Q_OBJECT
public:
explicit ElidedLabel(QWidget *parent = nullptr);
void setText(const QString &text);
const QString & text() const { return content; }
protected:
void paintEvent(QPaintEvent *event) override;
private:
QString content;
};
#endif // ELIDEDLABEL_H
//elidedlabel.cpp
#include "elidedlabel.h"
ElidedLabel::ElidedLabel(QWidget *parent)
: QLabel(parent)
{
}
void ElidedLabel::setText(const QString &newText)
{
content = newText;
update();
}
void ElidedLabel::paintEvent(QPaintEvent *event)
{
QLabel::paintEvent(event);
QPainter painter(this);
QFontMetrics fontMetrics = painter.fontMetrics();
QString elidedLine = fontMetrics.elidedText(content, Qt::ElideMiddle, width());
painter.drawText(QPoint(0, fontMetrics.ascent()), elidedLine);
}

riverofwind
- 525
- 4
- 17