为QPushButton设置背景图片

问题描述 投票:0回答:4

我正在努力为 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()));
}

我在样式表中使用的图像位于同一项目文件夹中。 有没有人有解决办法?

image qt4 background
4个回答
8
投票

你必须将 flat 属性设置为 true:

button1->setFlat(true);

您还必须设置自动填充背景 -

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);

(我的图像存储为资源)


3
投票

您的 CSS 选择器不正确。

你应该这样做:

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);

0
投票

如果有人需要 Python 中的解决方案,因为我在这里找不到任何东西:

    label = QLabel(self)
    label.setGeometry(self.butt_top_left.geometry())
    pixmap = QPixmap('path_to_your_symbol/symbol.png')
    pixmap = pixmap.scaled(label.size(), Qt.IgnoreAspectRatio)
    label.setPixmap(pixmap)
    label.show()

您正在创建一个标签,其位置正好在您的按钮上。这对我来说很有效。

© www.soinside.com 2019 - 2024. All rights reserved.