QSS爲Qt程序添加不同的樣式

添加 QSS 樣式文件

在 Qt 項目中新建一個或使用已有的 Qt Resource File,在資源文件下面新建一個普通文件,命名爲 Light.qsshtml

Light.qss 添加以下內容:git

這裏是模仿 bootstrap 的樣式格式,爲 QPushButton 添加幾種情景色,熟悉以後能夠自行添加更多的情景模式。github

編寫 QSS 樣式文件時推薦使用 VSCODE(由於 QtCreator 彷佛不支持高亮顯示該類型的文件,可能有插件能夠支持),上圖就是從 VSCODE 中截得圖,安裝 Qt for Python 這個插件後就能正常高亮這個文件了。bootstrap

導入 QSS 樣式

在 Qt 中導入樣式的方法有不少種,能夠直接設置 QApplication 對象的 style:app

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 個按鈕:ui

若是直接運行這個程序,你會看到按鈕仍是和上面的圖片中所顯示的那樣,沒有任何情景色的變化。咱們須要給各個按鈕設置不一樣的屬性:this

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

運行程序,再次點擊第一個按鈕,能夠看到以下圖所示的內容,第一個按鈕變成了綠色:

再點擊一次,它又會變成藍色。這樣就達到了動態改變樣式的目的。


Demo Project 的 github 地址

本文首發於 BriFuture 的 我的博客

參考

  1. Dynamic_Properties_and_Stylesheets
  2. customizing-using-dynamic-properties
相關文章
相關標籤/搜索