2014-02-10 71 views
8

我試圖在Qt5中更改QAbstractButton(QPushButton或QCheckBox)的背景顏色並且運氣不錯。Qt5 - 將背景顏色設置爲QPushButton和QCheckBox

這無助:

pButton->setAutoFillBackground(true); 
QPalette palette = pButton->palette(); 
palette.setColor(QPalette::Window, QColor(Qt::blue)); 
pButton->setPalette(palette); 
pButton->show(); 

如果我嘗試改變樣式表:

pButton->setStyleSheet("background-color: rgb(255,255,0);"); 

然後Qt的拋出了其手中,並且描繪出afwul前瞻性塊狀按鈕。

有一頁標題爲「How to change the background color of QWidget」,但它只是談論這兩種方法。

還有一個頁面「Qt Style Sheets Examples」,這意味着如果你想改變背景顏色,你必須接管繪製按鈕的所有方面,這似乎是矯枉過正。

我需要在Mac,Windows和Ubuntu Linux上運行它,如果我必須手動繪製關於按鈕的所有內容(每個平臺一次),那真的不是一件快樂的事情。

我錯過了一些明顯的東西嗎?

p.s. 「背景顏色」是指按鈕周圍的區域,而不是按鈕正面文字的顏色。

+1

你有沒有解決這個問題? – Alchete

+1

我沒有......看起來如果你使用默認的小部件,Qt使用QStyle「繪製」它們,這很好,因爲那麼你的小部件在所有不同的平臺上都是原生的,但不是很好,因爲定製不再是可能的。你可能能夠創建自己的QStyle派生類,並以某種方式搭載QStyle本身,但是我們決定在UI中完全不同的方向,繞過這個限制。 –

回答

10

我有同樣的問題,但終於得到了這個工作。我使用Qt 5與融合的顏色主題:

QPalette pal = button->palette(); 
pal.setColor(QPalette::Button, QColor(Qt::blue)); 
button->setAutoFillBackground(true); 
button->setPalette(pal); 
button->update(); 

的準確順序嘗試如上這些命令,如果仍然不能正常工作,請將您的主題,融合,然後再試一次。

祝你好運!

+0

我已經在linux和mac上試過了。奇怪的是,我使用的RGB QColor和Linux上它確實改變顏色,但沒有指定的,在Mac上根本沒有。我已經按照這個順序嘗試了上述命令。 – Lightbulb1

+3

如果您在按鈕上設置Flat(true),它將響應我的預期。雖然對其他人來說可能不是理想的結果。 – Lightbulb1

3

在樣式表中添加邊框:無;屬性。出於某種原因,這也會刪除默認的背景顏色。例如:background-color: rgba(46, 204, 113, 0.4); border: none;

+0

3年後,我有與Qt 5.8,Windows 8相同的問題。這解決了它,即使它是一個奇怪的行爲 – Phiber

6

更改對話框styleSheet屬性工作對我來說,這個屬性設置爲:

QPushButton:pressed { 
    background-color: qlineargradient(spread:pad, x1:0, y1:0, x2:0, y2:1, stop:0 rgba(60, 186, 162, 255), stop:1 rgba(98, 211, 162, 255)) 
} 
QPushButton { 
    background-color: #3cbaa2; border: 1px solid black; 
    border-radius: 5px; 
} 

QPushButton:disabled { 
    background-color: rgb(170, 170, 127) 
} 

enter image description here

1

試試這個:

QColor col = QColor(Qt::blue); 
if(col.isValid()) { 
    QString qss = QString("background-color: %1").arg(col.name()); 
    button->setStyleSheet(qss); 
} 
截至 the QT Forum by @goetz提到

我用Qcolor col的一些不同的定義作爲QColor col = QColor::fromRgb(144,238,144);,這對我很有用。