C++ – Custom styles for custom widgets in Qt

cqtqt4

Does anybody have experience with custom styled, custom widgets in Qt?
(I am using Qt 4.5)

The problems looks like this:

I want to develop some custom controls that are not based entirely on existing drawing primitives and sub-controls. Since the entire application should be skinnable, I want to rely on custom styles, possible on style sheets as well.

What I need to configure for those new controls are the following:

  • additional metrics
  • additional palette entries
  • additional style options

Digging on internet and documentation, I found out that I need to derive a new style class from one the QStyle sub-classes, and override polish method for adding new palette entries, and drawControl (and the other draw methods) for painting logic for custom control and custom parts.

I have two issues that bother me:

  1. Currently, there are different style classes for different styles, already implemented in Qt. (e.g. QMotifStyle, QWindowsStyle), each with different settings. Through inheritance, I would need to re-implement the painting and additional setup logic for each style, in order to properly integrate in all these styles. Do I have another alternative?

  2. I am still confused about how can style sheets be used with these custom styles. Can anybody point to a place where I can find more information than the one provided by Qt documentation? (The samples in Qt don't help me too much).

Best Answer

The style sheet problem will not be solved, as it will not on custom classes.

The extra goodies added to a custom style will not be understood and taken care by already existing classes. This is because C++ is a static language and there is no (clean and sane) way to monkey-patch the run-time classes. A potential solution is to use a proxy style which wraps a certain instance of standard QStyle subclasses. Depending on how much you want to achieve with it, you can refer to two articles: Cross-platform code and styles and Look 'n' Feel Q & A.

If I were you, I would not go with the QStyle approach. Afterall, you create custom widgets (e.g. FooSomething) so you can as well add create completely different custom styles (e.g. FooStyle), it does not even need to mimic QStyle. Of course then you still need to replicate similar functionalities, e.g. to support style sheet.