button->setStyleSheet("border-image:url(:/Icons/images/Sfondo.png);");
Or change stylesheet from designer.
题
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?
解决方案
button->setStyleSheet("border-image:url(:/Icons/images/Sfondo.png);");
Or change stylesheet from designer.
其他提示
ui->pushButton_5->setStyleSheet("backgroundimage:url(/home/Desktop/qtproject/ sample2/images /11.png);");
For Setting background in Qpushbutton
You can use this code, it worked for me : ui->pushButton_2->setStyleSheet("background-image:url(C://Users//XXXX//Desktop//menu//icon.png);");