2017-05-05 13 views
0

Qt C++を使用して、アイコンとテキストのボタンがいくつかあります。すべてのボタンのテキストが同じ長さを持っていないとして、アイコンが整列されていない。中央に配置されない可能性があり、QPushButton:アイコンとテキストを整列する方法

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

しかし、誰成功:

enter image description here

私が代わりにQToolButtonを使用しようとしましたテキスト、それになってしまった:

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; 
}; 

あなただけpromote featureを使用し、Qtのデザイナーからそれを使用したい場合。

+0

非常にいいです。ありがとう。より簡単な解決法を望んでいたが、それは機能する! – jpo38

+0

喜んで助けてください。より簡単な方法を見つけたらお知らせください。非常に便利です。 – cbuchart

関連する問題