简体   繁体   English

QPushButton:如何对齐图标和文本

[英]QPushButton: How to align icon and text

Using Qt C++, I have some buttons with icons and text.使用 Qt C++,我有一些带有图标和文本的按钮。 As the text of all buttons does not have the same length, icons are not aligned:由于所有按钮的文本长度不同,图标没有对齐:

在此处输入图片说明

I tried to use a QToolButton instead:我尝试使用 QToolButton 代替:

button->setToolButtonStyle( Qt::ToolButtonTextBesideIcon );
button->setSizePolicy( QSizePolicy( QSizePolicy::Policy::Expanding, button->sizePolicy().verticalPolicy() ) );

But no success, could not center the text, ended up with that:但是没有成功,无法将文本居中,结果是:

在此处输入图片说明

Is there a way to have icons be aligned vertically and also text remain centered, like that:有没有办法让图标垂直对齐并且文本保持居中,如下所示:

在此处输入图片说明

You can achieve it by sub-classing QPushButton .您可以通过子类化QPushButton来实现它。 Here an example with the minimum functionality:这是一个功能最少的示例:

class MyButton : public QPushButton {
public:
  explicit MyButton(QWidget* parent = nullptr) : QPushButton(parent) {}
  virtual ~MyButton() {}

  void setPixmap(const QPixmap& pixmap) { m_pixmap = pixmap; }

  virtual QSize sizeHint() const override {
    const auto parentHint = QPushButton::sizeHint();
    // add margins here if needed
    return QSize(parentHint.width() + m_pixmap.width(), std::max(parentHint.height(), m_pixmap.height()));
  }

protected:
  virtual void paintEvent(QPaintEvent* e) override {
    QPushButton::paintEvent(e);

    if (!m_pixmap.isNull()) {
      const int y = (height() - m_pixmap.height()) / 2; // add margin if needed
      QPainter painter(this);
      painter.drawPixmap(5, y, m_pixmap); // hardcoded horizontal margin
    }
  }

private:
  QPixmap m_pixmap;
};

If you want to use it from Qt Designer, just use the promote feature .如果您想从 Qt Designer 使用它,只需使用提升功能

here, you can see the simple answer of IGHOR : QPushButton icon aligned left with text centered在这里,您可以看到 IGHOR 的简单答案: QPushButton 图标左对齐,文本居中

Less code way without breaking UI style在不破坏 UI 风格的情况下,更少的代码方式

pushButton->setIcon(QApplication::style()->standardIcon(QStyle::SP_MessageBoxQuestion));
pushButton->setStyleSheet("text-align:left;");
pushButton->setLayout(new QGridLayout);

QLabel* textLabel = new QLabel("Hello world!");
textLabel->setAlignment(Qt::AlignRight | Qt::AlignVCenter); // or center
textLabel->setAttribute(Qt::WA_TransparentForMouseEvents, true);

pushButton->layout()->addWidget(textLabel);

Remember to send setText signals to textLabel instead of pushButton记住将 setText 信号发送到 textLabel 而不是 pushButton

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM