'QIcon not get properly sets on QPushButton

I have an application of qt to sets the icon for QPushButton. The code as follows:

widget.h :

 class Widget : public QWidget
 {
     Q_OBJECT

 public:
    explicit Widget(QWidget *parent = 0);
~Widget();

 private:
     Ui::Widget *ui;
 };

widget.cpp :

 Widget::Widget(QWidget *parent) :
 QWidget(parent),
 ui(new Ui::Widget)
 {
  ui->setupUi(this);

   QImage img(":/sample");
   QPixmap scaled = QPixmap::fromImage(img).scaled( QSize(ui->pushButton->size().width(),ui->pushButton->size().height()), Qt::KeepAspectRatioByExpanding );
   QIcon icon(scaled);
   ui->pushButton->setIconSize(QSize(ui->pushButton->size().width(),ui->pushButton->size().height()));
   ui->pushButton->setIcon(icon);
 }

I having the pushbutton on ui file. But the icon not covering as fully on pushbutton. I having the pushbutton size as (100,100). I have attached the screenshot of the result:

enter image description here



Solution 1:[1]

The problem with your approach is that you are setting the icon of pushbutton in constructor itself. Since your code is dependent on the size of button, this is a bad approach. The reason is, till the execution of constructor is over, the size is not fixed and therefore you end up with unexpected result. The solution is to set the size of icon during resize event of the mainwindow, this method will even allow to adjust if the pushbutton size changes during runtime.

First install event filter (copy this line in constructor)

this->installEventFilter(this);  

Now re implement a function called eventFilter

bool Widget::eventFilter(QObject *watched, QEvent *event)
{
    Q_UNUSED(watched)
    if(event->type() == QEvent::Resize){
        SetIcon();
    }
    return false;
}

where the defintion of SetIcon() is as below

void Widget::SetIcon()
{
    // Set the following variables according to your need
    QString IconPath = /*Path_of_your_icon*/;
    QPushButton *button = /*Your_Pushbutton*/;
    int Margin = /*Margin*/;

    button->setIcon(QIcon(QPixmap(IconPath)));
    QSize size;
    int width = button->height() - Margin ;
    int height = button->width() - Margin ;
    size.setHeight(height);
    size.setWidth(width);
    button->setIconSize(size);

}

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Gurushant