Reputation: 21514
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:
Upvotes: 3
Views: 17846
Reputation: 31
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
Upvotes: 3
Reputation: 11555
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.
Upvotes: 5