QPushButton
来实现。以下是最简功能的示例: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;
};
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);