Qt wiki will be updated on October 12th 2023 starting at 11:30 AM (EEST) and the maintenance will last around 2-3 hours. During the maintenance the site will be unavailable.
Elided Label
Jump to navigation
Jump to search
Just call this function and you're good to go.
//! Set the elide mode used for displaying text.
void setElideMode(Qt::TextElideMode elideMode) {
elideMode_ = elideMode;
updateGeometry();
}
#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:
ElidedLabel(QWidget '''parent = 0, Qt::WindowFlags f = 0);
ElidedLabel(const QString &txt, QWidget''' parent = 0, Qt::WindowFlags f = 0);
ElidedLabel(const QString &txt,
Qt::TextElideMode elideMode = Qt::ElideRight,
QWidget * parent = 0,
Qt::WindowFlags f = 0);
public:
//! Set the elide mode used for displaying text.
void setElideMode(Qt::TextElideMode elideMode) {
elideMode_ = elideMode;
updateGeometry();
}
//! Get the elide mode currently used to display text.
Qt::TextElideMode elideMode() const { return elideMode_; }
public: // QLabel overrides
void setText(const QString &);
protected: // QLabel overrides
void paintEvent(QPaintEvent ''');
void resizeEvent(QResizeEvent''');
protected:
//! Cache the elided text so as to not recompute it every paint event
void cacheElidedText(int w);
private:
Qt::TextElideMode elideMode_;
QString cachedElidedText;
};
#endif // ELIDEDLABEL_HPP
#include "ElidedLabel.h"
#include <QDebug>
#include <QPainter>
#include <QResizeEvent>
ElidedLabel::ElidedLabel(QWidget *parent, Qt::WindowFlags f)
: QLabel(parent, f) , elideMode_(Qt::ElideRight)
{
// setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
}
ElidedLabel::ElidedLabel(const QString &txt, QWidget *parent, Qt::WindowFlags f)
: QLabel(txt, parent, f) , elideMode_(Qt::ElideRight)
{
}
ElidedLabel::ElidedLabel(const QString &txt, Qt::TextElideMode elideMode,
QWidget *parent, Qt::WindowFlags f) : QLabel(txt, parent, f)
, elideMode_(elideMode)
{
}
void ElidedLabel::setText(const QString &txt) {
QLabel::setText(txt);
cacheElidedText(geometry().width());
}
void ElidedLabel::cacheElidedText(int w) {
cachedElidedText = fontMetrics().elidedText(text(), elideMode_, w, Qt::TextShowMnemonic);
}
void ElidedLabel::resizeEvent(QResizeEvent *e) {
QLabel::resizeEvent(e);
cacheElidedText(e->size().width());
}
void ElidedLabel::paintEvent(QPaintEvent *e) {
if(elideMode_ == Qt::ElideNone) {
QLabel::paintEvent(e);
} else {
QPainter p(this);
p.drawText(0, 0,
geometry().width(),
geometry().height(),
alignment(),
cachedElidedText);
}
}