2017-05-05 531 views
0

使用Qt C++,我有一些带有图标和文本的按钮。由于所有按钮的文本不具有相同的长度,图标不对齐:QPushButton:如何对齐图标和文字

enter image description here

我试图用一个QToolButton来代替:

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

但没有成功,不能居中文字,结束了认为:

enter image description here

有没有办法有图标的垂直对齐和LSO文本保持居中,这样的:

enter image description here

回答

3

您可以通过子类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; 
}; 

如果你想从Qt设计师使用它,只需使用promote feature

+0

非常好。谢谢。希望得到一个更简单的解决方案,但它的工作原理! – jpo38

+0

很高兴帮助。让我们知道如果你找到一个更简单的方法来做到这一点,它也会非常有用。 – cbuchart