2010-04-20 120 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);