|  | Home · Overviews · Examples |

# QStyle Class Reference
[com.trolltech.qt.gui module]

The `QStyle` class is an abstract base class that encapsulates the look and feel of a GUI. More...

Inherits `QObject`.

Inherited by `QCommonStyle`.

## Detailed Description

The `QStyle` class is an abstract base class that encapsulates the look and feel of a GUI.

Qt contains a set of `QStyle` subclasses that emulate the styles of the different platforms supported by Qt (`QWindowsStyle`, QMacStyle, `QMotifStyle`, etc.). By default, these styles are built into the QtGui library. Styles can also be made available as plugins.

Qt's built-in widgets use `QStyle` to perform nearly all of their drawing, ensuring that they look exactly like the equivalent native widgets. The diagram below shows a `QComboBox` in six different styles.

Topics:

- Setting a Style
- Developing Style-Aware Custom Widgets
- Creating a Custom Style
- Using a Custom Style
- Right-to-Left Desktops

### Setting a Style

The style of the entire application can be set using the QApplication::setStyle() function. It can also be specified by the user of the application, using the `-style` command-line option:

        ./myapplication -style motif

If no style is specified, Qt will choose the most appropriate style for the user's platform or desktop environment.

A style can also be set on an individual widget using the QWidget::setStyle() function.

### Developing Style-Aware Custom Widgets

If you are developing custom widgets and want them to look good on all platforms, you can use `QStyle` functions to perform parts of the widget drawing, such as `drawItemText`, `drawItemPixmap`, `drawPrimitive`, `drawControl`, and `drawComplexControl`.

Most `QStyle` draw functions take four arguments:

- an enum value specifying which graphical element to draw
- a `QStyleOption` specifying how and where to render that element
- a `QPainter` that should be used to draw the element
- a `QWidget` on which the drawing is performed (optional)

For example, if you want to draw a focus rectangle on your widget, you can write:

        void MyWidget::paintEvent(QPaintEvent * /* event */)
        {
            QPainter painter(this);

            QStyleOptionFocusRect option;
            option.initFrom(this);
            option.backgroundColor = palette().color(QPalette::Background);

            style()->drawPrimitive(QStyle::PE_FrameFocusRect, &option, &painter, this);
        }

`QStyle` gets all the information it needs to render the graphical element from `QStyleOption`. The widget is passed as the last argument in case the style needs it to perform special effects (such as animated default buttons on Mac OS X), but it isn't mandatory. In fact, you can use `QStyle` to draw on any paint device, not just widgets, by setting the `QPainter` properly.

`QStyleOption` has various subclasses for the various types of graphical elements that can be drawn. For example, `PE_FrameFocusRect` expects a `QStyleOptionFocusRect` argument.

To ensure that drawing operations are as fast as possible, `QStyleOption` and its subclasses have public data members. See the `QStyleOption` class documentation for details on how to use it.

For convenience, Qt provides the `QStylePainter` class, which combines a `QStyle`, a `QPainter`, and a `QWidget`. This makes it possible to write

            QStylePainter painter(this);
            ...
            painter.drawPrimitive(QStyle::PE_FrameFocusRect, option);

instead of

            QPainter painter(this);
            ...
            style()->drawPrimitive(QStyle::PE_FrameFocusRect, &option, &painter, this);

### Creating a Custom Style

If you want to design a custom look and feel for your application, the first step is to pick one of the base styles provided with Qt to build your custom style from. The choice will depend on which existing style resembles your style the most.

Depending on which parts of the base style you want to change, you must reimplement the functions that are used to draw those parts of the interface. To illustrate this, we will modify the look of the spin box arrows drawn by `QWindowsStyle`. The arrows are primitive elements that are drawn by the `drawPrimitive` function, so we need to reimplement that function. We need the following class declaration:

        class CustomStyle : public QWindowsStyle
        {
            Q_OBJECT

        public:
            CustomStyle()
            ~CustomStyle() {}

            void drawPrimitive(PrimitiveElement element, const QStyleOption *option,
                               QPainter *painter, const QWidget *widget) const;
        };

To draw its up and down arrows, `QSpinBox` uses the `PE_IndicatorSpinUp` and `PE_IndicatorSpinDown` primitive elements. Here's how to reimplement the `drawPrimitive` function to draw them differently:

        void CustomStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option,
                                        QPainter *painter, const QWidget *widget) const
        {
            if (element == PE_IndicatorSpinUp || element == PE_IndicatorSpinDown) {
                QPolygon points(3);
                int x = option->rect.x();
                int y = option->rect.y();
                int w = option->rect.width() / 2;
                int h = option->rect.height() / 2;
                x += (option->rect.width() - w) / 2;
                y += (option->rect.height() - h) / 2;

                if (element == PE_IndicatorSpinUp) {
                    points[0] = QPoint(x, y + h);
                    points[1] = QPoint(x + w, y + h);
                    points[2] = QPoint(x + w / 2, y);
                } else { // PE_SpinBoxDown
                    points[0] = QPoint(x, y);
                    points[1] = QPoint(x + w, y);
                    points[2] = QPoint(x + w / 2, y + h);
                }

                if (option->state & State_Enabled) {
                    painter->setPen(option->palette.mid().color());
                    painter->setBrush(option->palette.buttonText());
                } else {
                    painter->setPen(option->palette.buttonText().color());
                    painter->setBrush(option->palette.mid());
                }
                painter->drawPolygon(points);
            } else {
                QWindowsStyle::drawPrimitive(element, option, painter, widget);
            }
        }

Notice that we don't use the `widget` argument, except to pass it on to the QWindowStyle::drawPrimitive() function. As mentioned earlier, the information about what is to be drawn and how it should be drawn is specified by a `QStyleOption` object, so there is no need to ask the widget.

If you need to use the `widget` argument to obtain additional information, be careful to ensure that it isn't 0 and that it is of the correct type before using it. For example:

            QSpinBox *spinBox = qobject_cast<QSpinBox *>(widget);
            if (spinBox) {
            ...
            }

When implementing a custom style, you cannot assume that the widget is a `QSpinBox` just because the enum value is called `PE_IndicatorSpinUp` or `PE_IndicatorSpinDown`.

The documentation for the Styles example covers this topic in more detail.

### Using a Custom Style

There are several ways of using a custom style in a Qt application. The simplest way is call the QApplication::setStyle() static function before creating the `QApplication` object:

        #include <QtGui>

        #include "customstyle.h"

        int main(int argc, char *argv[])
        {
            QApplication::setStyle(new CustomStyle);
            QApplication app(argc, argv);
            QSpinBox spinBox;
            spinBox.show();
            return app.exec();
        }

You can call QApplication::setStyle() at any time, but by calling it before the constructor, you ensure that the user's preference, set using the `-style` command-line option, is respected.

You may want to make your style available for use in other applications, some of which may not be yours and are not available for you to recompile. The Qt Plugin system makes it possible to create styles as plugins. Styles created as plugins are loaded as shared objects at runtime by Qt itself. Please refer to the Qt Plugin documentation for more information on how to go about creating a style plugin.

Compile your plugin and put it into Qt's `plugins/styles` directory. We now have a pluggable style that Qt can load automatically. To use your new style with existing applications, simply start the application with the following argument:

        ./myapplication -style custom

The application will use the look and feel from the custom style you implemented.

### Right-to-Left Desktops

Languages written from right to left (such as Arabic and Hebrew) usually also mirror the whole layout of widgets, and require the light to come from the screen's top-right corner instead of top-left.

If you create a custom style, you should take special care when drawing asymmetric elements to make sure that they also look correct in a mirrored layout. An easy way to test your styles is to run applications with the `-reverse` command-line option or to call QApplication::setLayoutDirection() in your `main()` function.

Here are some things to keep in mind when making a style work well in a right-to-left environment:

- `subControlRect` and `subElementRect` return rectangles in screen coordinates
- QStyleOption::direction indicates in which direction the item should be drawn in
- If a style is not right-to-left aware it will display items as if it were left-to-right
- `visualRect`, `visualPos`, and `visualAlignment` are helpful functions that will translate from logical to screen representations.
- `alignedRect` will return a logical rect aligned for the current direction

See also `QStyleOption`, `QStylePainter`, Styles Example, and Implementing Styles and Style Aware Widgets.