2010-04-20 539 views
6

我很努力为QPushButton设置背景图片。直到现在还没有成功。以下是我的代码。为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())); 
} 

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

回答

6

必须设置平属性为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); 

(我的图像存储为资源)

+0

在上面的代码中,我应该调整我的图像调整到适合按钮或它会自动照顾? – 2010-04-20 06:26:27

+1

你可以去任何一个方向。最初我在编辑器中将图像大小调整为50x50,但后来决定要使用40x40 - “setIconSize()”将图标缩放为任何你想要的。 – 2010-04-20 14:21:15

+0

这是不正确的,你不必设置平面属性或自动填充背景。你可以简单地通过'setIcon(“:/ path/to/image.png”)加载图像。我通常会首先将图像加载到一个'QPixmap'中,以便它可以作为绘制设备使用,然后将Pixmap传递给任何需要它的元素。 – 2014-04-28 18:48:13

2

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