Qt Background Image for a QPushButton

Rudy Barbieri picture Rudy Barbieri · Oct 18, 2013 · Viewed 12.2k times · Source

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?

Answer

patriotyk picture patriotyk · Oct 18, 2013
button->setStyleSheet("border-image:url(:/Icons/images/Sfondo.png);");

Or change stylesheet from designer.