1 #include "ElidedLabel.h"
2
3 #include <QDebug>
4 #include <QPainter>
5 #include <QResizeEvent>
6
ElidedLabel(QWidget * parent,Qt::WindowFlags f)7 ElidedLabel::ElidedLabel(QWidget* parent, Qt::WindowFlags f)
8 : QLabel(parent, f)
9 , elideMode_(Qt::ElideRight)
10 {
11 // setSizePolicy(QSizePolicy::Ignored, QSizePolicy::Preferred);
12 }
13
ElidedLabel(const QString & txt,QWidget * parent,Qt::WindowFlags f)14 ElidedLabel::ElidedLabel(const QString& txt, QWidget* parent, Qt::WindowFlags f)
15 : QLabel(txt, parent, f)
16 , elideMode_(Qt::ElideRight)
17 {
18 }
19
ElidedLabel(const QString & txt,Qt::TextElideMode elideMode,QWidget * parent,Qt::WindowFlags f)20 ElidedLabel::ElidedLabel(const QString& txt, Qt::TextElideMode elideMode, QWidget* parent, Qt::WindowFlags f)
21 : QLabel(txt, parent, f)
22 , elideMode_(elideMode)
23 {
24 }
25
setText(const QString & txt)26 void ElidedLabel::setText(const QString& txt)
27 {
28 QLabel::setText(txt);
29 cacheElidedText(geometry().width());
30 }
31
cacheElidedText(int w)32 void ElidedLabel::cacheElidedText(int w)
33 {
34 cachedElidedText = fontMetrics().elidedText(text(), elideMode_, w, Qt::TextShowMnemonic);
35 }
36
resizeEvent(QResizeEvent * e)37 void ElidedLabel::resizeEvent(QResizeEvent* e)
38 {
39 QLabel::resizeEvent(e);
40 cacheElidedText(e->size().width());
41 }
42
paintEvent(QPaintEvent * e)43 void ElidedLabel::paintEvent(QPaintEvent* e)
44 {
45 if(elideMode_ == Qt::ElideNone)
46 {
47 QLabel::paintEvent(e);
48 }
49 else
50 {
51 QPainter p(this);
52 p.drawText(0, 0, geometry().width(), geometry().height(), alignment(), cachedElidedText);
53 }
54 }
55