[SOLVED] QIcon not get properly sets on QPushButton

Issue

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

Try passing Qt::IgnoreAspectRatio as the last argument of scaled, and see if the result fits your needs. If it doesn’t, maybe the image should be squared (i.e. same width and height).

Answered By – p-a-o-l-o

Answer Checked By – Candace Johnson (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *