4

I need to put an image from the internal resources as a background image of a QPushButton. I need also to adapt the size of the image to the size of the button. I have found here some way to do that, but nothing seems to work. In the last reply it was suggested the use of the following code:

QPixmap pixmap("image.jpg");
QPalette palette;    
QPushButton *button= new QPushButton(this);
palette.setBrush(button->backgroundRole(), QBrush(pixmap));
button->setFlat(true);
button->setAutoFillBackground(true);    
button->setPalette(palette);

So I took that code and changed it a bit 'cause I'm using a ui made with QTCreator:

void MyDialog::SetBgImage(QWidget *pButton)
{
    QPixmap pixmap(":/Icons/images/Sfondo.png");
    QPalette palette = pButton->palette();
    palette.setBrush(pButton->backgroundRole(), QBrush(pixmap)); // 1
    QPushButton *pPButton = qobject_cast<QPushButton *>(pButton);
    if (pPButton!=NULL)
           pPButton->setFlat(true);
    pButton->setAutoFillBackground(true);
   pButton->setPalette(palette); // 2

}

In the constructor I call it in this way:

SetBgImage(ui->pushButton_Button1);

when the dialog is showed the button is displayed correctly. Unfortunately when I close the dialog I get the following error message:

* glibc detected * ./MyAppName: malloc(): memory corruption: 0x0047dc78 ***

If I remove the line marked with //1 or the line marked with //2 the error disappear.

Any ideas?

Community
  • 1
  • 1
Rudy Barbieri
  • 389
  • 1
  • 4
  • 16

3 Answers3

8
button->setStyleSheet("border-image:url(:/Icons/images/Sfondo.png);");

Or change stylesheet from designer.

Kuba hasn't forgotten Monica
  • 95,931
  • 16
  • 151
  • 313
patriotyk
  • 497
  • 3
  • 13
0

ui->pushButton_5->setStyleSheet("backgroundimage:url(/home/Desktop/qtproject/ sample2/images /11.png);");

For Setting background in Qpushbutton

Bala Kumaran
  • 131
  • 3
  • 14
0

You can use this code, it worked for me : ui->pushButton_2->setStyleSheet("background-image:url(C://Users//XXXX//Desktop//menu//icon.png);");

ali.sh
  • 1
  • 3
  • Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Mar 04 '22 at 08:11