设置QPushButton的背景图片

9

我正在努力为QPushButton设置背景图片,但是一直没有成功。以下是我的代码。

appsWidget::appsWidget(QWidget *parent)
    :QWidget(parent)
{
    QPushButton *button1 = new QPushButton("SETTINGS",this);
    QPushButton *button2 = new QPushButton("TEST",this);
    QPushButton *button3 = new QPushButton("IE",this);

    button1->setStyleSheet("background-image:url(config.png)"); -> No success


    qDebug("appWidget initialized.");

    QHBoxLayout *layout = new QHBoxLayout;
    layout->addWidget(button1);
    layout->addWidget(button2);
    layout->addWidget(button3);
    this->setLayout(layout);
    connect(button1,SIGNAL(clicked()),this,SLOT(setClickIndex1()));
    connect(button2,SIGNAL(clicked()),this,SLOT(setClickIndex2()));
    connect(button3,SIGNAL(clicked()),this,SLOT(setClickIndex3()));
}

我在样式表中使用的图像位于同一项目文件夹中。 有人有解决方案吗?
3个回答

8

您需要将flat属性设置为true:

button1->setFlat(true);

您还需要设置autofillbackground属性 -

button1->setAutoFillBackground(true);

您可能想查看一下QToolButton,它不需要扁平化即可呈现图像。我正在编写的应用程序中使用它们,它们看起来非常漂亮:

m_showAddCommentButton = new QToolButton();
m_showAddCommentButton->setAutoFillBackground(true);
palette = m_showAddCommentButton->palette();
palette.setColor(QPalette::Button,QColor(82,110,166));
m_showAddCommentButton->setPalette(palette);
m_showAddCommentButton->setIcon(QIcon(":/uiImages/addComment_50_50.jpg"));
m_showAddCommentButton->setIconSize(QSize(40,40));
m_showAddCommentButton->setToolTip("Comment");
connect(m_showAddCommentButton, SIGNAL(clicked()),
        manager, SLOT(showAddComment()));
hLayout->addWidget(m_showAddCommentButton,0);

我的图片被存储为一个资源


在上面的代码中,我应该调整我的图像大小以适应按钮,还是它会自动处理? - Surjya Narayana Padhi
1
你可以选择任一种方式。最初我在编辑器中将图像外部调整为50x50大小,但后来决定使用40x40大小 - setIconSize()函数可按照需求缩放图标。 - Brian Roach
这不正确,您不必设置flat属性或自动填充背景。您只需通过setIcon(":/path/to/image.png")加载图像即可。我通常会先将图像加载到QPixmap中,以便将其用作绘画设备,然后将Pixmap传递给需要它的任何元素。 - Chef Pharaoh

3
你的CSS选择器不正确。你应该这样做:
```css p { /* your styles here */ } ```
button1->setStyleSheet("QPushButton{ background-image: url(config.png); }");

1

您可以使用刷子作为调色板元素来填充任何小部件的背景,对于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);

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