Qt QPushButton的背景图片

4
我需要将内部资源中的图像作为QPushButton的背景图像。我还需要调整图像的大小以适应按钮的大小。 我在这里找到了一些方法,但似乎没有什么起作用的。 在最后一个回复中,建议使用以下代码:
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);

因为我使用的是由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

}

在构造函数中,我以这种方式调用它:
SetBgImage(ui->pushButton_Button1);

当对话框显示时,按钮正确显示。不幸的是,当我关闭对话框时,我会得到以下错误消息:
* glibc detected * ./MyAppName:malloc():内存损坏:0x0047dc78 ***
如果我删除标有//1的行或标有//2的行,则错误消失。
有什么想法吗?
3个回答

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

或者从设计师那里更改样式表。


0

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

设置Qpushbutton的背景


0
你可以使用这段代码,它对我有效: ui->pushButton_2->setStyleSheet("background-image:url(C://Users//XXXX//Desktop//menu//icon.png);");

你的回答可以通过提供更多支撑信息来改进。请[编辑]以添加更多细节,例如引用或文档,以便他人可以确认您的答案是否正确。您可以在帮助中心找到有关如何编写好答案的更多信息。 - Community

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接