首页 > 解决方案 > 将 QLabel 对齐设置为右侧并在右侧剪切文本

问题描述

我正在用 C++ 编写一个 Qt 4.8(我们不能为这个项目使用更新的 Qt 版本)应用程序,我有各种 QLabels,它们必须右对齐,并且其文本在代码中动态设置。但是如果文本超过 QLabel 的大小,它会在左侧被剪裁。然而,所需的行为是剪辑右侧的文本。

例如,包含客户名称“Abraham Lincoln”的 QLabel 会将文本剪辑为“aham Lincoln”而不是“Abraham Li”。有没有内置的方法可以做到这一点,还是我必须根据文本长度动态移动和调整 QLabel 的大小?

标签: c++qt4.8

解决方案


QLabel不幸的是,我认为您无法完全实现您想要的。但是您可以尝试以一种方式管理QLabel它,使其以您需要的方式对齐/修剪。以下似乎工作......

#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;
};

当然,您可能需要添加额外的成员函数,具体取决于您当前的使用方式QLabel


推荐阅读