Qt 樣式錶是允許定製 Widget 外觀的強大機製,除瞭可能已有的,通過子類化 QStyle 。Qt 樣式錶的概念、術語和語法深受啓發被 HTML CSS (級聯樣式錶) ,但適應 Widget 世界。
話題:
樣式錶是可以設置的正文規範在整個應用程序使用 QApplication::setStyleSheet () 或在特定 Widget (及其子級) 使用 QWidget::setStyleSheet ()。若有在不同級彆設置多個樣式錶,Qt 將從所有那些設置樣式錶派生齣有效樣式錶。這稱為級聯。
例如,以下樣式錶指定所有 QLineEdit 應該使用黃色作為它們的背景色,且所有 QCheckBox 應該使用紅色作為文本顔色:
QLineEdit { background: yellow } QCheckBox { color: red }
對於這種定製,樣式錶強大得多比 QPalette . For example, it might be tempting to set the QPalette::Button role to red for a QPushButton to obtain a red push button. However, this wasn't guaranteed to work for all styles, because style authors are restricted by the different platforms' guidelines and (on Windows and macOS ) by the native theme engine.
Style sheets let you perform all kinds of customizations that are difficult or impossible to perform using QPalette alone. If you want yellow backgrounds for mandatory fields, red text for potentially destructive push buttons, or fancy check boxes, style sheets are the answer.
Style sheets are applied on top of the current Widget 樣式 , meaning that your applications will look as native as possible, but any style sheet constraints will be taken into consideration. Unlike palette fiddling, style sheets offer guarantees: If you set the background color of a QPushButton to be red, you can be assured that the button will have a red background in all styles, on all platforms. In addition, Qt Designer provides style sheet integration, making it easy to view the effects of a style sheet in different widget styles .
In addition, style sheets can be used to provide a distinctive look and feel for your application, without having to subclass QStyle . For example, you can specify arbitrary images for radio buttons and check boxes to make them stand out. Using this technique, you can also achieve minor customizations that would normally require subclassing several style classes, such as specifying a style hint 。 Style Sheet example depicted below defines two distinctive style sheets that you can try out and modify at will.
|
| Pagefold (摺頁) 主題運行在 Windows |
|
|
| Coffee (咖啡) 主題運行在 Ubuntu Linux | Pagefold theme running on macOS |
當樣式錶活動時, QStyle 返迴通過 QWidget::style () is a wrapper "style sheet" style, not the platform-specific style. The wrapper style ensures that any active style sheet is respected and otherwise forwards the drawing operations to the underlying, platform-specific style (e.g., QWindowsVistaStyle on Windows).
Since Qt 4.5, Qt style sheets fully supports macOS .