Dynamically resize QIcon without calling setSizeIcon()

前端 未结 2 644
无人共我
无人共我 2021-01-20 18:01

I\'m currently struggling with what should be an easy issue to solve. Many widgets support some sort of QSizePolicy. This includes the QPushbutton

2条回答
  •  余生分开走
    2021-01-20 18:25

    To persons who work in C++. Thanks a lot !

    pushbuttoniconautoresize.h

    #ifndef PUSHBUTTONIMAGEAUTOMATICRESIZE_H
    #define PUSHBUTTONIMAGEAUTOMATICRESIZE_H
    
    #include 
    
    class PushButtonIconAutoResize : public QPushButton
    {
        Q_OBJECT
    
    public:
        PushButtonIconAutoResize(const QString &text, QWidget *parent=0);
        ~PushButtonIconAutoResize();
    
    private:
        void paintEvent(QPaintEvent *event);
    
        int pad;
        int minSize;
    };
    
    #endif // PUSHBUTTONIMAGEAUTOMATICRESIZE_H
    

    pushbuttoniconautoresize.cpp

    #include "pushbuttoniconautoresize.h"
    
    #include 
    #include 
    #include 
    #include 
    #include 
    
    PushButtonIconAutoResize::PushButtonIconAutoResize(const QString &text, QWidget *parent)
        : QPushButton(text, parent)
    {
        pad = 4;
        minSize = 8;
    
        this->setSizePolicy(QSizePolicy(QSizePolicy::Expanding,QSizePolicy::Expanding));
    }
    
    PushButtonIconAutoResize::~PushButtonIconAutoResize()
    {
    
    }
    
    void PushButtonIconAutoResize::paintEvent( QPaintEvent *event )
    {
        QStylePainter painter(this);
    
        QStyleOptionButton opt;
        this->initStyleOption(&opt);
    
        QRect r = opt.rect;
    
        int h = r.height();
        int w = r.width();
        int iconSize = qMax(qMin(h, w) - 2 * this->pad, this->minSize);
    
        opt.iconSize = QSize(iconSize, iconSize);
    
        painter.drawControl(QStyle::CE_PushButton, opt);
    }
    

提交回复
热议问题