The Styles example illustrates how to create custom widget drawing styles using Qt, and demonstrates Qt’s predefined styles.
A style in Qt is a subclass of
QStyle or of one of its subclasses. Styles perform drawing on behalf of widgets. Qt provides a whole range of predefined styles, either built into the Qt Widgets module or found in plugins. Styles are usually customized by subclassing
QProxyStyle and reimplementing a few virtual functions. While
QProxyStyle provides a transparent way to customize either a specific style or the appropriate platform’s default style, Qt also provides
QCommonStyle as a convenient base for full custom style implementations.
In this example, the custom style is called
NorwegianWoodStyle and derives from
QProxyStyle . Its main features are the wooden textures used for filling most of the widgets and its round buttons and comboboxes.
To implement the style, we use some advanced features provided by
QPainter , such as
antialiasing (to obtain smoother button edges),
alpha blending (to make the buttons appeared raised or sunken), and
painter paths (to fill the buttons and draw the outline). We also use many features of
The example consists of the following classes:
QProxyStyleand implements the Norwegian Wood style.
QDialogsubclass that shows the most common widgets and allows the user to switch style dynamically.
NorwegianWoodStyle Class Definition#
Here’s the definition of the
class NorwegianWoodStyle(QProxyStyle): Q_OBJECT # public NorwegianWoodStyle() standardPalette = QPalette() def polish(widget): def unpolish(widget): pixelMetric(PixelMetric = int() widget) = QWidget() styleHint(StyleHint = int() widget, = QWidget() def drawPrimitive(element, option,): painter, = QPainter() def drawControl(control, option,): painter, = QPainter() # private def setTexture(palette, role,): image) = QImage() roundRectPath = QPainterPath(QRect rect) QPalette = mutable()
The public functions are all declared in
QProxyStyle ‘s grandparent class) and reimplemented here to override the Windows look and feel. The private functions are helper functions.
NorwegianWoodStyle Class Implementation#
We will now review the implementation of the
def standardPalette(self): if not m_standardPalette.isBrushSet(QPalette.Disabled, QPalette.Mid): brown = QColor(212, 140, 95) beige = QColor(236, 182, 120) slightlyOpaqueBlack = QColor(0, 0, 0, 63) backgroundImage = QImage(":/images/woodbackground.png") buttonImage = QImage(":/images/woodbutton.png") midImage = buttonImage.convertToFormat(QImage.Format_RGB32) painter = QPainter() painter.begin(midImage) painter.setPen(Qt.NoPen) painter.fillRect(midImage.rect(), slightlyOpaqueBlack) painter.end()
standardPalette() function is reimplemented from
QStyle . It returns a
QPalette with the style’s preferred colors and textures. Most styles don’t need to reimplement that function. The Norwegian Wood style reimplements it to set a “wooden” palette.
We start by defining a few
QColor s that we’ll need. Then we load two PNG images. The
: prefix in the file path indicates that the PNG files are embedded resources .
This texture is used as the background of most widgets. The wood pattern is horizontal.
This texture is used for filling push buttons and comboboxes. The wood pattern is vertical and more reddish than the texture used for the background.
midImage variable is initialized to be the same as
buttonImage, but then we use a
QPainter and fill it with a 25% opaque black color (a black with an
alpha channel of 63). The result is a somewhat darker image than
buttonImage. This image will be used for filling buttons that the user is holding down.
palette = QPalette(brown) palette.setBrush(QPalette.BrightText, Qt.white) palette.setBrush(QPalette.Base, beige) palette.setBrush(QPalette.Highlight, Qt.darkGreen) setTexture(palette, QPalette.Button, buttonImage) setTexture(palette, QPalette.Mid, midImage) setTexture(palette, QPalette.Window, backgroundImage) brush = palette.window() brush.setColor(brush.color().darker()) palette.setBrush(QPalette.Disabled, QPalette.WindowText, brush) palette.setBrush(QPalette.Disabled, QPalette.Text, brush) palette.setBrush(QPalette.Disabled, QPalette.ButtonText, brush) palette.setBrush(QPalette.Disabled, QPalette.Base, brush) palette.setBrush(QPalette.Disabled, QPalette.Button, brush) palette.setBrush(QPalette.Disabled, QPalette.Mid, brush) m_standardPalette = palette return m_standardPalette
We initialize the palette. Palettes have various
color roles , such as
Base (used for filling text editors, item views, etc.),
Text (used for foreground text), and
Window (used for the background of most widgets). Each role has its own
QBrush , which usually is a plain color but can also be a brush pattern or even a texture (a
In addition to the roles, palettes have several
color groups : active, disabled, and inactive. The active color group is used for painting widgets in the active window. The disabled group is used for disabled widgets. The inactive group is used for all other widgets. Most palettes have identical active and inactive groups, while the disabled group uses darker shades.
We initialize the
QPalette object with a brown color. Qt automatically derivates all color roles for all color groups from that single color. We then override some of the default values. For example, we use
darkGreen instead of the default (
darkBlue ) for the
Highlight role. The
setBrush() overload that we use here sets the same color or brush for all three color groups.
setTexture() function is a private function that sets the texture for a certain color role, while preserving the existing color in the
QBrush . A
QBrush can hold both a solid color and a texture at the same time. The solid color is used for drawing text and other graphical elements where textures don’t look good.
At the end, we set the brush for the disabled color group of the palette. We use
woodbackground.png as the texture for all disabled widgets, including buttons, and use a darker color to accompany the texture.
Let’s move on to the other functions reimplemented from
def polish(self, widget):
polish() overload is called once on every widget drawn using the style. We reimplement it to set the
WA_Hover attribute on
QPushButton s and
QComboBox es. When this attribute is set, Qt generates paint events when the mouse pointer enters or leaves the widget. This makes it possible to render push buttons and comboboxes differently when the mouse pointer is over them.
def unpolish(self, widget):
unpolish() overload is called to undo any modification done to the widget in
polish(). For simplicity, we assume that the flag wasn’t set before
polish() was called. In an ideal world, we would remember the original state for each widgets (e.g., using a
QWidget *, bool>) and restore it in
NorwegianWoodStyle::pixelMetric(PixelMetric = int()
pixelMetric() function returns the size in pixels for a certain user interface element. By reimplementing this function, we can affect the way certain widgets are drawn and their size hint. Here, we return 8 as the width around a shown in a
QComboBox , ensuring that there is enough place around the text and the arrow for the Norwegian Wood round corners. The default value for this setting in the Windows style is 2.
We also change the extent of
QScrollBar s, i.e., the height for a horizontal scroll bar and the width for a vertical scroll bar, to be 4 pixels more than in the Windows style. This makes the style a bit more distinctive.
For all other
PixelMetric elements, we use the Windows settings.
NorwegianWoodStyle::styleHint(StyleHint = int()
styleHint() function returns some hints to widgets or to the base style (in our case
QProxyStyle ) about how to draw the widgets. The Windows style returns
true for the
SH_DitherDisabledText hint, resulting in a most unpleasing visual effect. We override this behavior and return
false instead. We also return
true for the
SH_EtchDisabledText hint, meaning that disabled text is rendered with an embossed look.
def drawPrimitive(self, element,):
drawPrimitive() function is called by Qt widgets to draw various fundamental graphical elements. Here we reimplement it to draw
QComboBox with round corners. The button part of these widgets is drawn using the
PE_PanelButtonCommand primitive element.
option parameter, of type
QStyleOption , contains everything we need to know about the widget we want to draw on. In particular,
option->rect gives the rectangle within which to draw the primitive element. The
painter parameter is a
QPainter object that we can use to draw on the widget.
widget parameter is the widget itself. Normally, all the information we need is available in
painter, so we don’t need
widget. We can use it to perform special effects; for example, QMacStyle uses it to animate default buttons. If you use it, be aware that the caller is allowed to pass a null pointer.
We start by defining three
QColor s that we’ll need later on. We also put the x, y, width, and height components of the widget’s rectangle in local variables. The value used for the
semiTransparentWhite and for the
semiTransparentBlack color’s alpha channel depends on whether the mouse cursor is over the widget or not. Since we set the
WA_Hover attribute on
QPushButton s and
QComboBox es, we can rely on the
State_MouseOver flag to be set when the mouse is over the widget.
roundRect = roundRectPath(option.rect)
roundRect variable is a
QPainterPath . A
QPainterPath is is a vectorial specification of a shape. Any shape (rectangle, ellipse, spline, etc.) or combination of shapes can be expressed as a path. We will use
roundRect both for filling the button background with a wooden texture and for drawing the outline. The
roundRectPath() function is a private function; we will come back to it later.
brush = QBrush()
We define two variables,
darker, and initialize them based on the state of the button:
If the button is a
flat button, we use the
Windowbrush. We set
trueif the button is
If the button is currently held down by the user or in the
checkedstate, we use the
Midcomponent of the palette. We set
trueif the button is
Otherwise, we use the
Buttoncomponent of the palette.
The screenshot below illustrates how
QPushButton s are rendered based on their state:
To discover whether the button is flat or not, we need to cast the
option parameter to
QStyleOptionButton and check if the features member specifies the
Flat flag. The
qstyleoption_cast() function performs a dynamic cast; if
option is not a
qstyleoption_cast() returns a null pointer.
We turn on antialiasing on
QPainter . Antialiasing is a technique that reduces the visual distortion that occurs when the edges of a shape are converted into pixels. For the Norwegian Wood style, we use it to obtain smoother edges for the round buttons.
The first call to
fillPath() draws the background of the button with a wooden texture. The second call to
fillPath() paints the same area with a semi-transparent black color (a black color with an alpha channel of 63) to make the area darker if
darker is true.
penWidth = int()
Next, we draw the outline. The top-left half of the outline and the bottom-right half of the outline are drawn using different
QPen s to produce a 3D effect. Normally, the top-left half of the outline is drawn lighter whereas the bottom-right half is drawn darker, but if the button is
checked , we invert the two
QPen s to give a sunken look to the button.
x1 = x x2 = x + radius x3 = x + width - radius x4 = x + width if option.direction == Qt.RightToLeft: qSwap(x1, x4) qSwap(x2, x3) topHalf = QPolygon() topHalf << QPoint(x1, y) << QPoint(x4, y) << QPoint(x3, y + radius) << QPoint(x2, y + height - radius) << QPoint(x1, y + height) painter.setClipPath(roundRect) painter.setClipRegion(topHalf, Qt.IntersectClip) painter.setPen(topPen) painter.drawPath(roundRect)
We draw the top-left part of the outline by calling
drawPath() with an appropriate
clip region . If the layout direction is right-to-left instead of left-to-right, we swap the
x4 variables to obtain correct results. On right-to-left desktop, the “light” comes from the top-right corner of the screen instead of the top-left corner; raised and sunken widgets must be drawn accordingly.
The diagram below illustrates how 3D effects are drawn according to the layout direction. The area in red on the diagram corresponds to the
An easy way to test how a style looks in right-to-left mode is to pass the
-reverse command-line option to the application. This option is recognized by the
The bottom-right part of the outline is drawn in a similar fashion. Then we draw a one-pixel wide outline around the entire button, using the
WindowText component of the
This completes the
PE_PanelButtonCommand case of the
switch statement. Other primitive elements are handled by the base style. Let’s now turn to the other
NorwegianWoodStyle member functions:
def drawControl(self, element,):
drawControl() to draw the text on a
QPushButton in a bright color when the button is
option parameter points to a
QStyleOptionButton object (it normally should), we take a copy of the object and modify its palette member to make the
ButtonText be the same as the
BrightText component (unless the widget is disabled).
def setTexture(self, palette, role,):
setTexture() function is a private function that sets the
texture component of the
QBrush es for a certain
color role , for all three
color groups (active, disabled, inactive). We used it to initialize the Norwegian Wood palette in
def roundRectPath(self, QRect rect):
roundRectPath() function is a private function that constructs a
QPainterPath object for round buttons. The path consists of eight segments: four arc segments for the corners and four lines for the sides.
With around 250 lines of code, we have a fully functional custom style based on one of the predefined styles. Custom styles can be used to provide a distinct look to an application or family of applications.
For completeness, we will quickly review the
WidgetGallery class, which contains the most common Qt widgets and allows the user to change style dynamically. Here’s the class definition:
class WidgetGallery(QDialog): Q_OBJECT # public WidgetGallery(QWidget parent = None) # protected def changeEvent(arg__0): # private slots def changeStyle(styleName): def styleChanged(): def changePalette(): def advanceProgressBar(): # private def createTopLeftGroupBox(): def createTopRightGroupBox(): def createBottomLeftTabWidget(): def createBottomRightGroupBox(): def createProgressBar(): styleLabel = QLabel() styleComboBox = QComboBox() useStylePaletteCheckBox = QCheckBox() disableWidgetsCheckBox = QCheckBox() ...
def __init__(self, parent): super().__init__(parent) styleComboBox = QComboBox() defaultStyleName = QApplication.style().objectName() styleNames = QStyleFactory.keys() styleNames.append("NorwegianWood") for i in range(1, size): if defaultStyleName.compare(styleNames.at(i), Qt.CaseInsensitive) == 0: styleNames.swapItemsAt(0, i) break styleComboBox.addItems(styleNames) styleLabel = QLabel(tr("Style:")) styleLabel.setBuddy(styleComboBox) useStylePaletteCheckBox = QCheckBox(tr("Use style's standard palette")) useStylePaletteCheckBox.setChecked(True) disableWidgetsCheckBox = QCheckBox(tr("Disable widgets")) createTopLeftGroupBox() createTopRightGroupBox() createBottomLeftTabWidget() createBottomRightGroupBox() createProgressBar()
We start by creating child widgets. The Style combobox is initialized with all the styles known to
QStyleFactory , in addition to
create...() functions are private functions that set up the various parts of the
We connect the Style combobox to the
changeStyle() private slot, the Use style’s standard palette check box to the
changePalette() slot, and the Disable widgets check box to the child widgets’
topLayout = QHBoxLayout()
Finally, we put the child widgets in layouts.
def changeStyle(self, styleName):
When the user changes the style in the combobox, we call
setStyle() to dynamically change the style of the application.
If the user turns the Use style’s standard palette on, the current style’s
standard palette is used; otherwise, the system’s default palette is honored.
advanceProgressBar() slot is called at regular intervals to advance the progress bar. Since we don’t know how long the user will keep the Styles application running, we use a logarithmic formula: The closer the progress bar gets to 100%, the slower it advances.
We will review
createProgressBar() in a moment.
createTopLeftGroupBox() function creates the
QGroupBox that occupies the top-left corner of the
WidgetGallery. We skip the
createBottomRightGroupBox() functions, which are very similar.
def createProgressBar(self): progressBar = QProgressBar() progressBar.setRange(0, 10000) progressBar.setValue(0) timer = QTimer(self) timer.timeout.connect(self.advanceProgressBar) timer.start(1000)
createProgressBar(), we create a
QProgressBar at the bottom of the
WidgetGallery and connect its
timeout() signal to the