Files:
Images:
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 QtGui library or found in plugins. Custom styles are usually created by subclassing one of Qt's existing style and reimplementing a few virtual functions.
In this example, the custom style is called NorwegianWoodStyle and derives from QMotifStyle. 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:
Here's the definition of the NorwegianWoodStyle class:
class NorwegianWoodStyle : public QMotifStyle { Q_OBJECT public: NorwegianWoodStyle() {} void polish(QPalette &palette); void polish(QWidget *widget); void unpolish(QWidget *widget); int pixelMetric(PixelMetric metric, const QStyleOption *option, const QWidget *widget) const; int styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const; void drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; void drawControl(ControlElement control, const QStyleOption *option, QPainter *painter, const QWidget *widget) const; private: static void setTexture(QPalette &palette, QPalette::ColorRole role, const QPixmap &pixmap); static QPainterPath roundRectPath(const QRect &rect); };
The public functions are all declared in QStyle (QMotifStyle's grandparent class) and reimplemented here to override the Motif look and feel. The private functions are helper functions.
We will now review the implementation of the NorwegianWoodStyle class.
void NorwegianWoodStyle::polish(QPalette &palette) { QColor brown(212, 140, 95); QColor beige(236, 182, 120); QColor slightlyOpaqueBlack(0, 0, 0, 63); QPixmap backgroundImage(":/images/woodbackground.png"); QPixmap buttonImage(":/images/woodbutton.png"); QPixmap midImage = buttonImage; QPainter painter; painter.begin(&midImage); painter.setPen(Qt::NoPen); painter.fillRect(midImage.rect(), slightlyOpaqueBlack); painter.end();
The polish() function is reimplemented from QStyle. It takes a QPalette as a reference and adapts the palette to fit the style. 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 QColors that we'll need. Then we load two PNG images. The : prefix in the file path indicates that the PNG files are embedded resources.
woodbackground.png This texture is used as the background of most widgets. The wood pattern is horizontal. | |
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); QBrush brush = palette.background(); brush.setColor(brush.color().dark()); 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); }
We initialize the palette. Palettes have various color roles, such as QPalette::Base (used for filling text editors, item views, etc.), QPalette::Text (used for foreground text), and QPalette::Background (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 Qt::darkGreen instead of the default (Qt::darkBlue) for the QPalette::Highlight role. The QPalette::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.
Let's move on to the other functions reimplemented from QMotifStyle:
void NorwegianWoodStyle::polish(QWidget *widget) { if (qobject_cast<QPushButton *>(widget) || qobject_cast<QComboBox *>(widget)) widget->setAttribute(Qt::WA_Hover, true); }
This QStyle::polish() overload is called once on every widget drawn using the style. We reimplement it to set the Qt::WA_Hover attribute on QPushButtons and QComboBoxes. 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.
void NorwegianWoodStyle::unpolish(QWidget *widget) { if (qobject_cast<QPushButton *>(widget) || qobject_cast<QComboBox *>(widget)) widget->setAttribute(Qt::WA_Hover, false); }
This QStyle::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, const QStyleOption *option, const QWidget *widget) const { switch (metric) { case PM_ComboBoxFrameWidth: return 8; case PM_ScrollBarExtent: return QMotifStyle::pixelMetric(metric, option, widget) + 4; default: return QMotifStyle::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 Motif style is 2.
We also change the extent of QScrollBars, 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 Motif style. This makes the style a bit more distinctive.
For all other QStyle::PixelMetric elements, we use the Motif settings.
int NorwegianWoodStyle::styleHint(StyleHint hint, const QStyleOption *option, const QWidget *widget, QStyleHintReturn *returnData) const { switch (hint) { case SH_DitherDisabledText: return int(false); case SH_EtchDisabledText: return int(true); default: return QMotifStyle::styleHint(hint, option, widget, returnData); } }
The styleHint() function returns some hints to widgets or to the base style (in our case QMotifStyle) about how to draw the widgets. The Motif style returns true for the QStyle::SH_DitherDisabledText hint, resulting in a most unpleasing visual effect. We override this behavior and return false instead. We also return true for the QStyle::SH_EtchDisabledText hint, meaning that disabled text is rendered with an embossed look (as QWindowsStyle does).
void NorwegianWoodStyle::drawPrimitive(PrimitiveElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { switch (element) { case PE_PanelButtonCommand: { int delta = (option->state & State_MouseOver) ? 64 : 0; QColor slightlyOpaqueBlack(0, 0, 0, 63); QColor semiTransparentWhite(255, 255, 255, 127 + delta); QColor semiTransparentBlack(0, 0, 0, 127 - delta); int x, y, width, height; 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 QStyle::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 QColors 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 Qt::WA_Hover attribute on QPushButtons and QComboBoxes, we can rely on the QStyle::State_MouseOver flag to be set when the mouse is over the widget.
QPainterPath roundRect = roundRectPath(option->rect); int 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.
QBrush brush; bool darker; const QStyleOptionButton *buttonOption = qstyleoption_cast<const QStyleOptionButton *>(option); if (buttonOption && (buttonOption->features & QStyleOptionButton::Flat)) { brush = option->palette.background(); darker = (option->state & (State_Sunken | State_On)); } else { if (option->state & (State_Sunken | State_On)) { brush = option->palette.mid(); darker = !(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:
The screenshot below illustrates how QPushButtons 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 QStyleOptionButton::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.
The first call to QPainter::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.
int penWidth; if (radius < 10) penWidth = 3; else if (radius < 20) penWidth = 5; else penWidth = 7; QPen topPen(semiTransparentWhite, penWidth); QPen bottomPen(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 QPens 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 QPens to give a sunken look to the button.
int x1 = x; int x2 = x + radius; int x3 = x + width - radius; int x4 = x + width; if (option->direction == Qt::RightToLeft) { qSwap(x1, x4); qSwap(x2, x3); } QPolygon topHalf; 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 QPainter::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:
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.
QPolygon 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.foreground().color()); painter->setClipping(false); painter->drawPath(roundRect); painter->restore(); } break; default: QMotifStyle::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 Foreground component of the QPalette.
This completes the QStyle::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:
void NorwegianWoodStyle::drawControl(ControlElement element, const QStyleOption *option, QPainter *painter, const QWidget *widget) const { switch (element) { case CE_PushButtonLabel: { QStyleOptionButton myButtonOption; const QStyleOptionButton *buttonOption = qstyleoption_cast<const 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()); } } } QMotifStyle::drawControl(element, &myButtonOption, painter, widget); } break; default: QMotifStyle::drawControl(element, option, painter, widget); } }
We reimplement QStyle::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 QPalette::ButtonText be the same as the QPalette::BrightText component (unless the widget is disabled).
void NorwegianWoodStyle::setTexture(QPalette &palette, QPalette::ColorRole role, const QPixmap &pixmap) { for (int i = 0; i < QPalette::NColorGroups; ++i) { QColor color = palette.brush(QPalette::ColorGroup(i), role).color(); palette.setBrush(QPalette::ColorGroup(i), role, QBrush(color, pixmap)); } }
The setTexture() function is a private function that sets the texture component of the QBrushes for a certain color role, for all three color groups (active, disabled, inactive). We used it to initialize the Norwegian Wood palette in polish(QPalette &).
QPainterPath NorwegianWoodStyle::roundRectPath(const QRect &rect) { int radius = qMin(rect.width(), rect.height()) / 2; int diam = 2 * radius; int x1, y1, x2, y2; rect.getCoords(&x1, &y1, &x2, &y2); QPainterPath path; 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.
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 : public QDialog { Q_OBJECT public: WidgetGallery(QWidget *parent = 0); private slots: void changeStyle(const QString &styleName); void changePalette(); void advanceProgressBar(); private: void createTopLeftGroupBox(); void createTopRightGroupBox(); void createBottomLeftTabWidget(); void createBottomRightGroupBox(); void createProgressBar(); QPalette originalPalette; QLabel *styleLabel; QComboBox *styleComboBox; QCheckBox *useStylePaletteCheckBox; QCheckBox *disableWidgetsCheckBox; ... };
Here's the WidgetGallery constructor:
WidgetGallery::WidgetGallery(QWidget *parent) : QDialog(parent) { originalPalette = QApplication::palette(); styleComboBox = new QComboBox; styleComboBox->addItem("NorwegianWood"); styleComboBox->addItems(QStyleFactory::keys()); styleLabel = new QLabel(tr("&Style:")); styleLabel->setBuddy(styleComboBox); useStylePaletteCheckBox = new QCheckBox(tr("&Use style's standard palette")); useStylePaletteCheckBox->setChecked(true); disableWidgetsCheckBox = new 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.
connect(styleComboBox, SIGNAL(activated(QString)), this, SLOT(changeStyle(QString))); connect(useStylePaletteCheckBox, SIGNAL(toggled(bool)), this, SLOT(changePalette())); connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), topLeftGroupBox, SLOT(setDisabled(bool))); connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), topRightGroupBox, SLOT(setDisabled(bool))); connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), bottomLeftTabWidget, SLOT(setDisabled(bool))); connect(disableWidgetsCheckBox, SIGNAL(toggled(bool)), bottomRightGroupBox, SLOT(setDisabled(bool)));
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.
QHBoxLayout *topLayout = new QHBoxLayout; topLayout->addWidget(styleLabel); topLayout->addWidget(styleComboBox); topLayout->addStretch(1); topLayout->addWidget(useStylePaletteCheckBox); topLayout->addWidget(disableWidgetsCheckBox); QGridLayout *mainLayout = new 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")); changeStyle("NorwegianWood"); }
Finally, we put the child widgets in layouts.
void WidgetGallery::changeStyle(const QString &styleName)
{
if (styleName == "NorwegianWood") {
QApplication::setStyle(new NorwegianWoodStyle);
} else {
QApplication::setStyle(QStyleFactory::create(styleName));
}
changePalette();
}
When the user changes the style in the combobox, we call QApplication::setStyle() to dynamically change the style of the application.
void WidgetGallery::changePalette() { if (useStylePaletteCheckBox->isChecked()) QApplication::setPalette(QApplication::style()->standardPalette()); else QApplication::setPalette(originalPalette); }
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.
For the Norwegian Wood style, this makes no difference because we always override the palette with our own palette in NorwegianWoodStyle::polish().
void WidgetGallery::advanceProgressBar() { int curVal = progressBar->value(); int 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.
void WidgetGallery::createTopLeftGroupBox() { topLeftGroupBox = new QGroupBox(tr("Group 1")); radioButton1 = new QRadioButton(tr("Radio button 1")); radioButton2 = new QRadioButton(tr("Radio button 2")); radioButton3 = new QRadioButton(tr("Radio button 3")); radioButton1->setChecked(true); checkBox = new QCheckBox(tr("Tri-state check box")); checkBox->setTristate(true); checkBox->setCheckState(Qt::PartiallyChecked); QVBoxLayout *layout = new 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.
void WidgetGallery::createProgressBar() { progressBar = new QProgressBar; progressBar->setRange(0, 10000); progressBar->setValue(0); QTimer *timer = new QTimer(this); connect(timer, SIGNAL(timeout()), this, SLOT(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.