[Qt-interest] layout problems with QLabel with automatic eliding

Andrew Batishko abatishko at attensity.com
Thu Aug 13 18:58:18 CEST 2009


I wanted a class that would allow me to display a label that would take 
up as much space as possible without forcing the window to resize, and 
would automatically elide if the text was longer than could be 
displayed. I came up with the class below.

The problem is that this only works properly for cases where the label 
is placed in a QVBoxLayout, or in a QHBoxLayout where it's the only item 
in the layout with a stretch factor of 1.

This means that it doesn't work (for example) in a case where you want 
the label immediately followed (no extra space) by a "..." button, and 
then followed by extra unused space, something such as the following 
where "val1, val2, val3" are the auto-eliding label part.

|                                                           |
| Items: val1, val2, val3 [...]                 [] checkbox |
|                                                           |

Has anyone successfully put something like this together or have any 
ideas on how to accomplish this? I've tried messing around with various 
options on size policies and such, but with no luck.

Andrew

class AutoSizeLabel:public QLabel {
   Q_OBJECT
  public:
   AutoSizeLabel(const QString &text, QWidget *parent):QLabel(parent, f) {
     setSizePolicy(QSizePolicy(QSizePolicy::Ignored, 
QSizePolicy::Preferred));
     setText(text);
   }

   QString text(void) const { return fullText; }

  public slots:
   void setText(const QString &newText) {
     fullText = newText;
     QString elided = fontMetrics().elidedText(fullText, Qt::ElideRight, 
width());
     if (elided == fullText) {
       setToolTip(QString());
       QLabel::setText(fullText);
     }
     else {
       setToolTip(fullText);
       QLabel::setText(elided);
     }
   }

  protected:
   virtual void resizeEvent(QResizeEvent *) {
     setText(fullText);
   }

  private:
   QString fullText;
};





More information about the Qt-interest-old mailing list