Qt Style Sheets and Custom Painting Example

From Qt Wiki
Revision as of 16:55, 14 January 2015 by Maintenance script (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)
Jump to navigation Jump to search

Qt Style Sheets and Custom Painting Example

Introduction

This example demonstrates:

  1. use of qt style sheets
  2. use of Q_PROPERTY
  3. how to combine 1 and 2 with custom painting

In this example we have some custom widget that has reimplemented paintEvent function and inside, some custom painting is performed. We’ll see how to set custom colors for for shapes and lines via Qt Style Sheet mechanism. Thanks to it, we can easily change the colors inside the .qss file without recompiling the program.

Example Source code

swidget.h
swidget.cpp
main.cpp
sheet.qss

Code Walkthrough

We need to define our custom widget and assign new properties for further. In this case we need two custom color properties. One for line color and one for rectangle color.

Methods required by new properties:

We’ll reimplement the paintEvent

Private members will hold our Q_PROPERTY values

swidget.cpp
Paint event reimplementation. Drawing of line that goes across the widget and rectangle is performed in paintEvent for simplicty.

Define the setters and getters for lineColor and rectColor properties.
NOTE: we’re using qDebug() to make sure that our setters are being called in further widget restyling.

Let’s go into main.cpp now.
We’ll create very simple gui app that will show our custom widget:

Open the sheet.qss file that holds qproperties for this application. If open is succeedded get data in QString ssheet and apply stylle sheet to QApplication object.

Show widget and enter main event loop.

Inside sheet.qss we’re defining line and rectangle color for SWidget

Please note that all SWidget widget we’ll be styled in the same way.

In Case that we have:
and want custom look of each of them, we need to add names for them:

Noe, sheet.qss may look like this:

Now we can just modify the qss file to change appearance of our custom widget.

Categories: