简体   繁体   中英

QPushButton: How to align icon and text

Using Qt C++, I have some buttons with icons and text. As the text of all buttons does not have the same length, icons are not aligned:

在此处输入图片说明

I tried to use a QToolButton instead:

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 . 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 .

here, you can see the simple answer of IGHOR : QPushButton icon aligned left with text centered

Less code way without breaking UI style

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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