Elided Label

From Qt Wiki
Revision as of 12:46, 17 December 2018 by Christian Ehrlicher (talk | contribs) (Updated to match current coding style, removed unneeded ctors, ...)

(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to: navigation, search

En Ar Bg De El Es Fa Fi Fr Hi Hu It Ja Kn Ko Ms Nl Pl Pt Ru Sq Th Tr Uk Zh

Make sure to set the horizontal size policy to minimum and just call this function and you're good to go:

// Set the elide mode used for displaying text.
void ElidedLabel::setElideMode(Qt::TextElideMode elideMode)
{
    m_elideMode = elideMode;
    m_cachedText.clear();
    update();
}
#ifndef ELIDEDLABEL_H
#define ELIDEDLABEL_H

#include <QLabel>

// MIT - Yash : Speedovation.com [ Picked from internet and modified. if owner needs to add or change license do let me know.]

class ElidedLabel : public QLabel 
{
    Q_OBJECT
public:
    using QLabel::QLabel;
    // Set the elide mode used for displaying text.
    void setElideMode(Qt::TextElideMode elideMode);
    // Get the elide mode currently used to display text.
    Qt::TextElideMode elideMode() const { return m_elideMode; }

protected:
    void paintEvent(QPaintEvent *e) override;
    void resizeEvent(QResizeEvent *e) override;

private:
    void updateCachedTexts();

private:
    Qt::TextElideMode m_elideMode = Qt::ElideRight;
    QString m_cachedElidedText;
    QString m_cachedText;
};

#endif // ELIDEDLABEL_HPP
#include "ElidedLabel.h"

#include <QPaintEvent>
#include <QResizeEvent>

void ElidedLabel::setElideMode(Qt::TextElideMode elideMode)
{
    m_elideMode = elideMode;
    m_cachedText.clear();
    update();
}

void ElidedLabel::resizeEvent(QResizeEvent *e)
{
    QLabel::resizeEvent(e);
    m_cachedText.clear();
}

void ElidedLabel::paintEvent(QPaintEvent *e)
{
    if (m_elideMode == Qt::ElideNone)
        return QLabel::paintEvent(e);

    updateCachedTexts();
    QLabel::setText(m_cachedElidedText);
    QLabel::paintEvent(e);
    QLabel::setText(m_cachedText);
}

void ElidedLabel::updateCachedTexts()
{
    // setText() is not virtual ... :/
    const auto txt = text();
    if (m_cachedText == txt)
        return;
    m_cachedText = txt;
    const QFontMetrics fm(fontMetrics());
    m_cachedElidedText = fm.elidedText(text(),
                                       m_elideMode,
                                       width(),
                                       Qt::TextShowMnemonic);
    // make sure to show at least the first character
    if (!m_cachedText.isEmpty())
    {
      const QString showFirstCharacter = m_cachedText.at(0) + QStringLiteral("...");
      setMinimumWidth(fm.horizontalAdvance(showFirstCharacter) + 1);
    }
}