使用样式表定制 Qt Widgets

当使用样式表时,每个 Widget 被视为具有 4 个同心矩形的框:边距矩形、边框矩形、铺垫矩形及内容矩形。Box 模型将进一步详细描述这。

Box 模型

4 个同心矩形在概念上的出现如下所示:

  • 边距位于边框外。
  • 边框绘制在边距和铺垫之间。
  • 铺垫位于边框内,在边框和实际内容之间。
  • 内容是移除边距、边框和铺垫后,原始 Widget 或子控件剩下的东西。

The margin , border-width ,和 padding 特性默认为 0。在此情况下,所有 4 矩形 ( margin , border , padding ,和 content ) 准确重合。

可以为 Widget 指定背景使用 background-image 特性。默认情况下,background-image 仅在边框内区域绘制。可以改变这使用 background-clip 特性。可以使用 background-repeat and background-origin 来控制背景图像的重复和原点。

A background-image does not scale with the size of the widget. To provide a "skin" or background that scales along with the widget size, one must use border-image . Since the border-image property provides an alternate background, it is not required to specify a background-image when border-image is specified. In the case, when both of them are specified, the border-image draws over the background-image.

此外, image property may be used to draw an image over the border-image. The image specified does not tile or stretch and when its size does not match the size of the widget, its alignment is specified using the image-position property. Unlike background-image and border-image, one may specify a SVG in the image property, in which case the image is scaled automatically according to the widget size.

渲染规则的步骤如下所示:

  • Set clip for entire rendering operation (border-radius)
  • Draw the background (background-image)
  • Draw the border (border-image, border)
  • Draw overlay image (image)

子控件

A widget is considered as a hierarchy (tree) of subcontrols drawn on top of each other. For example, the QComboBox draws the drop-down sub-control followed by the down-arrow sub-control. A QComboBox is thus rendered as follows:

  • 渲染 QComboBox { } 规则
  • Render the QComboBox::drop-down { } rule
  • Render the QComboBox::down-arrow { } rule

Sub-controls share a parent-child relationship. In the case of QComboBox , the parent of down-arrow is the drop-down and the parent of drop-down is the widget itself. Sub-controls are positioned within their parent using the subcontrol-position and subcontrol-origin 特性。

一旦定位,子控件就可以被样式化使用 Box 模型 .

注意: 采用复杂 Widget,譬如 QComboBox and QScrollBar , if one property or sub-control is customized, all the other properties or sub-controls must be customized as well.