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

는 A A 아이콘은 수직으로 정렬 할 수 있습니다하는 방법과 거기에 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

관련 문제