2017-05-05 229 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