c++qt4.8

Set QLabel Alignment to right and also clip text on the right


I'm writing a Qt 4.8 (we cannot use newer Qt versions for this project) Application in C++ and I have various QLabels which have to be right-aligned and whose text is set dynamically in the code. But if the text exceeds the size of the QLabel it is clipped on the left side. The desired behavior however is to clip the text on the right side.

For example a QLabel containing the customer name "Abraham Lincoln" clips the text to "aham Lincoln" instead of "Abraham Li". Is there a built-in way to do this or would I have to dynamically move and resize the QLabel depending on the text length?


Solution

  • I don't think you can achieve exactly what you want with just a QLabel unfortunately. But you could try managing a QLabel in such a way that it aligns/trims in the way you require. The following seems to work...

    #include <QFontMetrics>
    #include <QLabel>
    
    class label: public QWidget {
      using super = QWidget;
    public:
      explicit label (const QString &text, QWidget *parent = nullptr)
        : super(parent)
        , m_label(text, this)
        {
        }
      virtual void setText (const QString &text)
        {
          m_label.setText(text);
          fixup();
        }
      virtual QString text () const
        {
          return(m_label.text());
        }
    protected:
      virtual void resizeEvent (QResizeEvent *event) override
        {
          super::resizeEvent(event);
          m_label.resize(size());
          fixup();
        }
    private:
      void fixup ()
        {
    
          /*
           * If the text associated with m_label has a width greater than the
           * width of this widget then align the text to the left so that it is
           * trimmed on the right.  Otherwise it should be right aligned.
           */
          if (QFontMetrics(font()).boundingRect(m_label.text()).width() > width())
            m_label.setAlignment(Qt::AlignLeft | Qt::AlignVCenter);
          else
            m_label.setAlignment(Qt::AlignRight | Qt::AlignVCenter);
        }
      QLabel m_label;
    };
    

    Of course you may have to add extra member functions depending on exactly how you are currently using QLabel.