添加 QSS 樣式文件
在 Qt 項目中新建一個或使用已有的 Qt Resource File
,在資源文件下面新建一個普通文件,命名為 Light.qss
:
為 Light.qss
添加如下內容:
這里是模仿 bootstrap 的樣式格式,為 QPushButton 添加幾種情景色,熟悉之后可以自行添加更多的情景模式。
編寫 QSS 樣式文件時推薦使用 VSCODE(因為 QtCreator 似乎不支持高亮顯示該類型的文件,可能有插件可以支持),上圖就是從 VSCODE 中截得圖,安裝 Qt for Python
這個插件后就能正常高亮這個文件了。
導入 QSS 樣式
在 Qt 中導入樣式的方法有很多種,可以直接設置 QApplication 對象的 style:
qApp->setStyleSheet("QLineEdit { background-color: yellow }");
或者對某個 QWidget 對象設置 style:
myDialog->setStyleSheet("QLineEdit { background-color: yellow }");
你可以像我一樣做,在 MainWindow 的構造函數中添加如下語句:
// MainWindow::MainWindow()
ui->setupUi(this);
QFile styleFile(":/Light.qss");
styleFile.open(QFile::ReadOnly);
QString style = QString::fromUtf8(styleFile.readAll());
setStyleSheet(style);
styleFile.close();
MainWindow 的 ui 文件很簡單,僅有 3 個按鈕:
如果直接運行這個程序,你會看到按鈕還是和上面的圖片中所顯示的那樣,沒有任何情景色的變化。我們需要給各個按鈕設置不同的屬性:
// set property
ui->primary->setProperty("variable", "primary");
ui->success->setProperty("variable", "success");
ui->warning->setProperty("variable", "warning");
再運行程序,圖片就變成這樣的多種顏色風格的了:
動態改變樣式
上面更改完按鈕的樣式后,實際上圖片樣式就固定下來了,做個小測試:
void MainWindow::on_primary_clicked()
{
if(ui->primary->property("variable").toString() == "primary") {
ui->primary->setProperty("variable", "success");
} else {
ui->primary->setProperty("variable", "primary");
}
}
添加這段槽函數代碼,執行程序,點擊上面第一個按鈕,顏色並不會變化。以下是摘自官方的說明
Limitations
There are limitations to using this trick. The main one is that the style will not update itself automatically when the value of a property referenced from the style sheet changes. Instead, you must manually trigger an update of the visual appearance of a widget when a styled property changes.
為了動態改變按鈕的樣式,我們還要添加一些代碼:
ui->primary->style()->unpolish(ui->primary);
ui->primary->style()->polish(ui->primary);
運行程序,再次點擊第一個按鈕,可以看到如下圖所示的內容,第一個按鈕變成了綠色:
再點擊一次,它又會變成藍色。這樣就達到了動態改變樣式的目的。
本文首發於 BriFuture 的 個人博客