[Solved] Shortening a label



  • I have a directory and file name in a QLabel. If the text is too long, it is making my window too wide. I have played with all of the size policy options I can think of but haven't been able to make it allow the window to get narrower.

    I'd like to either find the option to allow me to resize the window despite this QLabel's width or trip the contents of the QLabel to fit into the window. In other languages, I've calculated the width of the label, picked a spot in the middle and replaced enough characters with elipses to make it fit. Is there a routine already written to do that (along with integration procedures for someone getting used to Qt)?

    Thanks!
    SRG


  • Lifetime Qt Champion

    I think you are looking for:
    http://qt-project.org/doc/qt-4.8/qfontmetricsf.html#elidedText

    Hope it helps



  • It's fairly easy to add eliding to a QLabel subclass.

    elidelabel.h
    @
    #ifndef ELIDELABEL_H
    #define ELIDELABEL_H

    #include <QLabel>

    class ElideLabel : public QLabel
    {
    Q_OBJECT
    Q_PROPERTY(Qt::TextElideMode elideMode READ elideMode WRITE setElideMode)

    public:
    ElideLabel(QWidget* parent = 0);
    ElideLabel(const QString &text, QWidget* parent = 0);
    ~ElideLabel();

    void setElideMode(Qt::TextElideMode mode);
    Qt::TextElideMode elideMode() const;

    QSize minimumSizeHint() const;

    protected:
    virtual void paintEvent(QPaintEvent * event);

    private:
    Qt::TextElideMode m_elideMode;
    };

    #endif // ELIDELABEL_H
    @

    elidelabel.cpp
    @
    #include "elidelabel.h"
    #include <QPainter>

    ElideLabel::ElideLabel(QWidget* parent)
    : QLabel(parent)
    {
    m_elideMode = Qt::ElideNone;
    }

    ElideLabel::ElideLabel(const QString &text, QWidget* parent) : QLabel(text, parent)
    {
    m_elideMode = Qt::ElideNone;
    }

    ElideLabel::~ElideLabel()
    {
    }

    void ElideLabel::setElideMode(Qt::TextElideMode mode)
    {
    m_elideMode = mode;
    }

    Qt::TextElideMode ElideLabel::elideMode() const
    {
    return m_elideMode;
    }

    void ElideLabel::paintEvent(QPaintEvent * event)
    {
    if (m_elideMode == Qt::ElideNone)
    {
    QLabel::paintEvent(event);
    }
    else
    {
    QFrame::paintEvent(event);
    QPainter painter(this);
    QRect r = contentsRect();
    painter.drawText(r, alignment(), fontMetrics().elidedText(text(), m_elideMode, r.width()));
    }
    }

    QSize ElideLabel::minimumSizeHint() const
    {
    if (m_elideMode != Qt::ElideNone)
    {
    const QFontMetrics& fm = fontMetrics();
    QSize size(fm.width("..."), fm.height());
    return size;
    }

    return QLabel::minimumSizeHint();
    }
    @



  • Fantastic. Thanks to both of you.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.