Warning

This section contains snippets that were automatically translated from C++ to Python and may contain errors.

Styles Example#

The Styles example illustrates how to create custom widget drawing styles using Qt, and demonstrates Qt’s predefined styles.

../_images/styles-enabledwood.png

Screenshot of the Styles example

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 QBrush and QPalette .

The example consists of the following classes:

  • NorwegianWoodStyle inherits from QProxyStyle and implements the Norwegian Wood style.

  • WidgetGallery is a QDialog subclass that shows the most common widgets and allows the user to switch style dynamically.

NorwegianWoodStyle Class Definition#

Here’s the definition of the NorwegianWoodStyle class:

class NorwegianWoodStyle(QProxyStyle):

    Q_OBJECT
# public
    NorwegianWoodStyle()
    QPalette standardPalette() override
    def polish(widget):
    def unpolish(widget):
    int pixelMetric(PixelMetric metric, QStyleOption option,
                    QWidget widget) override
    int styleHint(StyleHint hint, QStyleOption option,
                  QWidget widget, QStyleHintReturn returnData) override
    def drawPrimitive(element, option,):
                       QPainter painter, QWidget widget) override
    def drawControl(control, option,):
                     QPainter painter, QWidget widget) override
# private
    def setTexture(palette, role,):
                           image) = QImage()
    roundRectPath = QPainterPath(QRect rect)
    QPalette = mutable()

The public functions are all declared in QStyle ( 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 NorwegianWoodStyle class.

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()

The 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 .

woodbackground1

woodbackground.png

This texture is used as the background of most widgets. The wood pattern is horizontal.

woodbutton2

woodbutton.png

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.

The 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 QPixmap ).

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.

The 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.

../_images/styles-disabledwood.png

Let’s move on to the other functions reimplemented from QProxyStyle :

def polish(self, widget):        if (QPushButton(widget)
        def QComboBox(widget)):
    widget.setAttribute(Qt.WA_Hover, True)

This 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):        if (QPushButton(widget)
        def QComboBox(widget)):
    widget.setAttribute(Qt.WA_Hover, False)

This 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 QMap < QWidget *, bool>) and restore it in unpolish().

int NorwegianWoodStyle.pixelMetric(PixelMetric metric,                                        QStyleOption option,
                                QWidget widget)


if metric == PM_ComboBoxFrameWidth:
    return 8
elif metric == PM_ScrollBarExtent:
    return QProxyStyle.pixelMetric(metric, option, widget) + 4
else:
    return QProxyStyle.pixelMetric(metric, option, widget)

The 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.

int NorwegianWoodStyle.styleHint(StyleHint hint, QStyleOption option,                                      QWidget widget,
                              QStyleHintReturn returnData)


if hint == SH_DitherDisabledText:
    return int(False)
elif hint == SH_EtchDisabledText:
    return int(True)
else:
    return QProxyStyle.styleHint(hint, option, widget, returnData)

The 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,):                                           QStyleOption option,
                                   QPainter painter,
                                   QWidget widget)


if element == PE_PanelButtonCommand:

        delta = (option.state  State_MouseOver) if 64 else 0
        slightlyOpaqueBlack = QColor(0, 0, 0, 63)
        semiTransparentWhite = QColor(255, 255, 255, 127 + delta)
        semiTransparentBlack = QColor(0, 0, 0, 127 - delta)
        x, = int()
        option.rect.getRect(x, y, width, height)

The drawPrimitive() function is called by Qt widgets to draw various fundamental graphical elements. Here we reimplement it to draw QPushButton and QComboBox with round corners. The button part of these widgets is drawn using the PE_PanelButtonCommand primitive element.

The 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.

The widget parameter is the widget itself. Normally, all the information we need is available in option and 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)        radius = qMin(width, height) / 2

The 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()        darker = bool()
buttonOption =
        QStyleOptionButton(option)
if (buttonOption
        and (buttonOption.features  QStyleOptionButton.Flat)) {
    brush = option.palette.window()
    darker = (option.state  (State_Sunken | State_On))
else:
    if option.state  (State_Sunken | State_On):
        brush = option.palette.mid()
        darker = not (option.state  State_Sunken)
    else:
        brush = option.palette.button()
        darker = False

We define two variables, brush and darker, and initialize them based on the state of the button:

  • If the button is a flat button , we use the Window brush. We set darker to true if the button is down or checked .

  • If the button is currently held down by the user or in the checked state, we use the Mid component of the palette. We set darker to true if the button is checked .

  • Otherwise, we use the Button component of the palette.

The screenshot below illustrates how QPushButton s are rendered based on their state:

../_images/styles-woodbuttons.png

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 QStyleOptionButton , qstyleoption_cast() returns a null pointer.

painter.save()        painter.setRenderHint(QPainter.Antialiasing, True)        painter.fillPath(roundRect, brush)        if darker:        painter.fillPath(roundRect, slightlyOpaqueBlack)

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.

../_images/styles-aliasing.png

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()                    if radius < 10:
                penWidth = 3
            elif radius < 20:
                penWidth = 5
else:
                penWidth = 7
            topPen = QPen(semiTransparentWhite, penWidth)
            bottomPen = QPen(semiTransparentBlack, penWidth)
            if option.state  (State_Sunken | State_On):
                qSwap(topPen, bottomPen)

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 down or 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 x1, x2, x3, and 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 topHalf polygon:

../_images/styles-3d.png

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 QApplication constructor.

    bottomHalf = topHalf
    bottomHalf[0] = QPoint(x4, y + height)
    painter.setClipPath(roundRect)
    painter.setClipRegion(bottomHalf, Qt.IntersectClip)
    painter.setPen(bottomPen)
    painter.drawPath(roundRect)
    painter.setPen(option.palette.windowText().color())
    painter.setClipping(False)
    painter.drawPath(roundRect)
    painter.restore()

break        else:        QProxyStyle.drawPrimitive(element, option, painter, widget)

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 QPalette .

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,):                                         QStyleOption option,
                                 QPainter painter,
                                 QWidget widget)


if element == CE_PushButtonLabel:

        myButtonOption = QStyleOptionButton()
        buttonOption =
                QStyleOptionButton(option)
        if buttonOption:
            myButtonOption = buttonOption
            if (myButtonOption.palette.currentColorGroup()
                    != QPalette.Disabled) {
                if myButtonOption.state  (State_Sunken | State_On):
                    myButtonOption.palette.setBrush(QPalette.ButtonText,
                            myButtonOption.palette.brightText())



        QProxyStyle.drawControl(element, myButtonOption, painter, widget)

    break
else:
    QProxyStyle.drawControl(element, option, painter, widget)

We reimplement drawControl() to draw the text on a QPushButton in a bright color when the button is down or checked .

If the 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,):                                        QImage image)

for i in range(0, QPalette.NColorGroups):
    brush = QBrush(image)
    brush.setColor(palette.brush(QPalette.ColorGroup(i), role).color())
    palette.setBrush(QPalette.ColorGroup(i), role, brush)

The 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 standardPalette.

def roundRectPath(self, QRect rect):        radius = qMin(rect.width(), rect.height()) / 2
diam = 2 * radius
x1, = int()
rect.getCoords(x1, y1, x2, y2)
path = QPainterPath()
path.moveTo(x2, y1 + radius)
path.arcTo(QRect(x2 - diam, y1, diam, diam), 0.0, +90.0)
path.lineTo(x1 + radius, y1)
path.arcTo(QRect(x1, y1, diam, diam), 90.0, +90.0)
path.lineTo(x1, y2 - radius)
path.arcTo(QRect(x1, y2 - diam, diam, diam), 180.0, +90.0)
path.lineTo(x1 + radius, y2)
path.arcTo(QRect(x2 - diam, y2 - diam, diam, diam), 270.0, +90.0)
path.closeSubpath()
return path

The 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.

WidgetGallery Class#

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()            ...

Here’s the WidgetGallery constructor:

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 NorwegianWood. The create...() functions are private functions that set up the various parts of the WidgetGallery.

styleComboBox.textActivated.connect(                self.changeStyle)
useStylePaletteCheckBox.toggled.connect(
        self.changePalette)
disableWidgetsCheckBox.toggled.connect(
        topLeftGroupBox.setDisabled)
disableWidgetsCheckBox.toggled.connect(
        topRightGroupBox.setDisabled)
disableWidgetsCheckBox.toggled.connect(
        bottomLeftTabWidget.setDisabled)
disableWidgetsCheckBox.toggled.connect(
        bottomRightGroupBox.setDisabled)

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’ setDisabled() slot.

topLayout = QHBoxLayout()        topLayout.addWidget(styleLabel)
topLayout.addWidget(styleComboBox)
topLayout.addStretch(1)
topLayout.addWidget(useStylePaletteCheckBox)
topLayout.addWidget(disableWidgetsCheckBox)
mainLayout = QGridLayout()
mainLayout.addLayout(topLayout, 0, 0, 1, 2)
mainLayout.addWidget(topLeftGroupBox, 1, 0)
mainLayout.addWidget(topRightGroupBox, 1, 1)
mainLayout.addWidget(bottomLeftTabWidget, 2, 0)
mainLayout.addWidget(bottomRightGroupBox, 2, 1)
mainLayout.addWidget(progressBar, 3, 0, 1, 2)
mainLayout.setRowStretch(1, 1)
mainLayout.setRowStretch(2, 1)
mainLayout.setColumnStretch(0, 1)
mainLayout.setColumnStretch(1, 1)
setLayout(mainLayout)
setWindowTitle(tr("Styles"))
styleChanged()

Finally, we put the child widgets in layouts.

def changeStyle(self, styleName):            if styleName == "NorwegianWood":
        QApplication.setStyle(NorwegianWoodStyle())
else:
        QApplication.setStyle(QStyleFactory.create(styleName))

When the user changes the style in the combobox, we call setStyle() to dynamically change the style of the application.

def changePalette(self):        QApplication.setPalette(useStylePaletteCheckBox.isChecked() ?
    QApplication.style().standardPalette() : QPalette())

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.

def advanceProgressBar(self):        curVal = progressBar.value()
maxVal = progressBar.maximum()
progressBar.setValue(curVal + (maxVal - curVal) / 100)

The 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.

def createTopLeftGroupBox(self):        topLeftGroupBox = QGroupBox(tr("Group 1"))
radioButton1 = QRadioButton(tr("Radio button 1"))
radioButton2 = QRadioButton(tr("Radio button 2"))
radioButton3 = QRadioButton(tr("Radio button 3"))
radioButton1.setChecked(True)
checkBox = QCheckBox(tr("Tri-state check box"))
checkBox.setTristate(True)
checkBox.setCheckState(Qt.PartiallyChecked)
layout = QVBoxLayout()
layout.addWidget(radioButton1)
layout.addWidget(radioButton2)
layout.addWidget(radioButton3)
layout.addWidget(checkBox)
layout.addStretch(1)
topLeftGroupBox.setLayout(layout)

The createTopLeftGroupBox() function creates the QGroupBox that occupies the top-left corner of the WidgetGallery. We skip the createTopRightGroupBox(), createBottomLeftTabWidget(), and 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)

In createProgressBar(), we create a QProgressBar at the bottom of the WidgetGallery and connect its timeout() signal to the advanceProgressBar() slot.

Example project @ code.qt.io