Qt 样式表

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 style , 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 .