Elide Text in Middle for QLabel C++

Viewed 37

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!

1 Answers

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);
}
Related