Qt Background Image for a QPushButton

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

Or change stylesheet from designer.

Share:
13,028
Rudy Barbieri
Author by

Rudy Barbieri

Updated on June 04, 2022

Comments

  • Rudy Barbieri
    Rudy Barbieri almost 2 years

    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?