Qt
Internal/Contributor docs for the Qt SDK. Note: These are NOT official API docs; those are found at https://doc.qt.io/
Loading...
Searching...
No Matches
qstylekitstyle.cpp
Go to the documentation of this file.
1// Copyright (C) 2026 The Qt Company Ltd.
2// SPDX-License-Identifier: LicenseRef-Qt-Commercial OR LGPL-3.0-only OR GPL-2.0-only OR GPL-3.0-only
3// Qt-Security score:significant reason:default
4
7#include <QtWidgets/qstyleoption.h>
8#include <QtWidgets/qstyle.h>
9#include <QtWidgets/qapplication.h>
10#if QT_CONFIG(scrollarea)
11# include <QtWidgets/qabstractscrollarea.h>
12#endif
13#if QT_CONFIG(itemviews)
14# include <QtWidgets/qabstractitemview.h>
15#endif
16#if QT_CONFIG(lineedit)
17# include <QtWidgets/qlineedit.h>
18#endif
19#if QT_CONFIG(pushbutton)
20# include <QtWidgets/qpushbutton.h>
21#endif
22#if QT_CONFIG(checkbox)
23# include <QtWidgets/qcheckbox.h>
24#endif
25#if QT_CONFIG(radiobutton)
26# include <QtWidgets/qradiobutton.h>
27#endif
28#if QT_CONFIG(combobox)
29# include <QtWidgets/qcombobox.h>
30#endif
31#if QT_CONFIG(slider)
32# include <QtWidgets/qslider.h>
33#endif
34#if QT_CONFIG(dial)
35# include <QtWidgets/qdial.h>
36#endif
37#if QT_CONFIG(scrollbar)
38# include <QtWidgets/qscrollbar.h>
39#endif
40#if QT_CONFIG(spinbox)
41# include <QtWidgets/qspinbox.h>
42#endif
43#if QT_CONFIG(progressbar)
44# include <QtWidgets/qprogressbar.h>
45#endif
46#if QT_CONFIG(textedit)
47# include <QtWidgets/qtextedit.h>
48# include <QtWidgets/qplaintextedit.h>
49#endif
50#if QT_CONFIG(tabbar)
51# include <QtWidgets/qtabbar.h>
52#endif
53#if QT_CONFIG(tabwidget)
54# include <QtWidgets/qtabwidget.h>
55#endif
56#if QT_CONFIG(toolbar)
57# include <QtWidgets/qtoolbar.h>
58#endif
59#if QT_CONFIG(toolbutton)
60# include <QtWidgets/qtoolbutton.h>
61#endif
62#if QT_CONFIG(groupbox)
63# include <QtWidgets/qgroupbox.h>
64#endif
65#if QT_CONFIG(menu)
66# include <QtWidgets/qmenu.h>
67# include <QtWidgets/qmenubar.h>
68#endif
69#if QT_CONFIG(label)
70# include <QtWidgets/qlabel.h>
71#endif
72#include <QtWidgets/private/qwidget_p.h>
73#include <QtCore/private/qobject_p.h>
74#include <QtGui/qpainter.h>
75#include <QtGui/qpainterpath.h>
76#include <QtGui/qpainterstateguard.h>
77#include <QtGui/qstylehints.h>
78#include <QtCore/qloggingcategory.h>
79#include <QtCore/qnumeric.h>
80#include <QtQml/private/qqmlcomponent_p.h>
81#include <QtQml/qqmlengine.h>
82#include <QtQuick/private/qquicktransition_p.h>
83#include <QtLabsStyleKit/private/qqstylekit_p.h>
84#include <QtLabsStyleKit/private/qqstylekitcontrolproperties_p.h>
85#include <QtLabsStyleKit/private/qqstylekitstyle_p.h>
86
88
89Q_STATIC_LOGGING_CATEGORY(lcStyleKit, "qt.labs.stylekit")
90
91/*!
92 \class QStyleKitStyle
93 \inmodule QtLabsStyleKit
94 \ingroup appearance
95 \since 6.12
96 \preliminary
97
98 \brief The QStyleKitStyle class applies a \l {Qt Labs StyleKit} style
99 to Qt Widgets.
100
101 QStyleKitStyle is a QStyle implementation that uses a \l StyleKit \l Style
102 to style Qt Widgets. The \l Style is a QML file that declaratively describes
103 the visual design (colors, sizes, radii, borders, and other properties)
104 for each widget type and state. QStyleKitStyle uses those property values
105 to paint each widget entirely with QPainter. Qt Quick and the scene graph
106 play no part in the rendering.
107
108 This separation means the same \l Style QML file can drive both
109 Qt Quick Controls and Qt Widgets, sharing one design definition across
110 both systems.
111
112 \note StyleKit is a Qt Labs module, and its API may change between
113 Qt releases.
114
115 \section1 Loading a Style
116
117 A style is a QML file whose root object is a \l Style. To load it,
118 pass the file path to the constructor or to \l setStylePath():
119
120 \if !defined(qtforpython)
121 \code
122 auto *style = new QStyleKitStyle(QStringLiteral(":/styles/MyStyle.qml"));
123 QApplication::setStyle(style);
124 \endcode
125 \else
126 \code
127 style = QStyleKitStyle(":/styles/MyStyle.qml")
128 QApplication.setStyle(style)
129 \endcode
130 \endif
131
132 QStyleKitStyle loads the Style with an internal QQmlEngine that the
133 QStyleKitStyle instance owns. If the path is invalid or the root object
134 is not a \l Style, QStyleKitStyle emits a warning and keeps the
135 previously loaded style. Until a style loads successfully, the widgets
136 use an empty fallback style.
137
138 \section1 Themes
139
140 A Style can define one or more named \l {Theme}{themes}. Call
141 \l setThemeName() to select the active theme, and read
142 \l availableThemeNames to list the themes a Style offers. The special
143 theme name \c System makes the style follow the platform color scheme:
144 when the OS color scheme changes, QStyleKitStyle recreates the active
145 theme and repolishes all widgets.
146
147 \section1 Widget to StyleKit control mapping
148
149 Each Qt Widgets class is mapped to a StyleKit control type, which
150 determines which control entry in the \l Style applies to it. Use the
151 corresponding control entry to configure visual properties for that
152 widget type, including individual parts of the widget such as its
153 background, indicator, and handle. See \l ControlStyleProperties for the
154 full list of stylable properties.
155
156 Properties not set in a specific control entry fall back through the
157 control type hierarchy: for example, \c button falls back to
158 \c abstractButton, which falls back to \c control.
159
160 \table
161 \header
162 \li Qt Widgets class
163 \li StyleKit control
164 \row
165 \li QPushButton (flat)
166 \li \l {StylableControls::flatButton}{flatButton}
167 \row
168 \li QPushButton
169 \li \l {StylableControls::button}{button}
170 \row
171 \li QCheckBox
172 \li \l {StylableControls::checkBox}{checkBox}
173 \row
174 \li QRadioButton
175 \li \l {StylableControls::radioButton}{radioButton}
176 \row
177 \li QComboBox
178 \li \l {StylableControls::comboBox}{comboBox}
179 \row
180 \li QSlider
181 \li \l {StylableControls::slider}{slider}
182 \row
183 \li QDial
184 \li \l {StylableControls::dial}{dial}
185 \row
186 \li QScrollBar
187 \li \l {StylableControls::scrollBar}{scrollBar}
188 \row
189 \li QSpinBox, QDoubleSpinBox
190 \li \l {StylableControls::spinBox}{spinBox}
191 \row
192 \li QProgressBar
193 \li \l {StylableControls::progressBar}{progressBar}
194 \row
195 \li QLineEdit
196 \li \l {StylableControls::textField}{textField}
197 \row
198 \li QTextEdit, QPlainTextEdit
199 \li \l {StylableControls::textArea}{textArea}
200 \row
201 \li QTabBar
202 \li \l {StylableControls::tabBar}{tabBar}
203 \row
204 \li QTabWidget
205 \li \l {StylableControls::page}{page}
206 \row
207 \li QToolBar
208 \li \l {StylableControls::toolBar}{toolBar}
209 \row
210 \li QToolButton
211 \li \l {StylableControls::toolButton}{toolButton}
212 \row
213 \li QGroupBox
214 \li \l {StylableControls::groupBox}{groupBox}
215 \row
216 \li QFrame
217 \li \l {StylableControls::frame}{frame}
218 \row
219 \li QLabel
220 \li \l {StylableControls::label}{label}
221 \row
222 \li QMenu
223 \li \l {StylableControls::menu}{menu}
224 \row
225 \li QMenuBar
226 \li \l {StylableControls::menuBar}{menuBar}
227 \row
228 \li Everything else
229 \li \l {StylableControls::control}{control}
230 \endtable
231
232 QStyleKitStyle does not yet support widgets outside this table;
233 \l QCommonStyle paints them instead. Conversely, some control entries in
234 \l StylableControls have no Qt Widgets equivalent, and
235 QStyleKitStyle ignores them when styling widgets.
236
237 \section2 Sub-controls within a widget
238
239 Each sub-control of a widget maps to its own control entry in the
240 \l Style, which lets you style the sub-controls individually.
241
242 \table
243 \header
244 \li Sub-control
245 \li StyleKit control
246 \row
247 \li \l QStyledItemDelegate items -- the default delegate for all Qt item views,
248 including the \l QComboBox popup list
249 \li \l {StylableControls::itemDelegate}{itemDelegate}
250 \row
251 \li The same items, when user-checkable (that is, when they show
252 a check indicator)
253 \li \l {StylableControls::checkDelegate}{checkDelegate};
254 falls back to \c itemDelegate for anything not set explicitly
255 \row
256 \li Individual tabs in a \l QTabBar
257 \li \l {StylableControls::tabButton}{tabButton}
258 \row
259 \li \l QMenu items
260 \li \l {StylableControls::menuItem}{menuItem}
261 \row
262 \li Separators in a \l QMenu
263 \li \l {StylableControls::menuSeparator}{menuSeparator}
264 \row
265 \li \l QMenuBar items
266 \li \l {StylableControls::menuBarItem}{menuBarItem}
267 \row
268 \li Separators in a \l QToolBar
269 \li \l {StylableControls::toolSeparator}{toolSeparator}
270 \row
271 \li The \l QComboBox popup list container
272 \li \l {StylableControls::popup}{popup}
273 \endtable
274
275 \section1 Known limitations
276
277 QStyleKitStyle does not support the following StyleKit features:
278
279 \list
280 \li \b{Shadows} -- QStyleKitStyle ignores shadow definitions.
281 \li \b{Delegate scale above 1.0 on a control's background} -- a
282 widget cannot paint outside its own rectangle, so QStyleKitStyle
283 clips the scaled background at the widget edge. Use
284 \l {DelegateStyle::}{margins} to inset the background and reserve
285 room for it to grow. Scaling indicators, handles, and foregrounds
286 still works.
287 \li \b{Variations} -- QStyleKitStyle does not yet apply a
288 \l StyleVariation set on a widget instance.
289 \li \b{Custom controls} -- QStyleKitStyle does not yet style custom
290 widgets declared with \l CustomControl.
291 \li \b{Custom delegates} -- QStyleKitStyle ignores the
292 \l {DelegateStyle::}{delegate} property and always uses its
293 built-in rendering.
294 \endlist
295
296 \sa QStyle, QCommonStyle, {Qt Labs StyleKit}, Style, Theme
297*/
298
299/*!
300 \property QStyleKitStyle::stylePath
301 \brief the path to the QML \l Style file driving this style.
302
303 The value is a path to a local file or to a file in the resource file
304 system, (for example, \c{:/styles/MyStyle.qml} or \c{qrc:/qt/qml/MyQmlModule/Style.qml}).
305 QStyleKitStyle resolves a relative path against the application's working directory.
306 The file must contain a QML component whose root object is a \l Style.
307 Setting this property reloads the style. If the new file does not load,
308 QStyleKitStyle emits a warning and keeps the previously loaded style
309 and style path.
310*/
311
312/*!
313 \property QStyleKitStyle::themeName
314 \brief the name of the active theme.
315
316 The value must be one of the entries in \l availableThemeNames. That
317 list includes the special name \c System, which makes the style follow
318 the platform color scheme. The comparison ignores case.
319
320 Setting this property repolishes all widgets so that they repaint with
321 the new theme. If the name matches no theme, the \l Style emits a
322 warning and applies no theme.
323*/
324
325/*!
326 \property QStyleKitStyle::availableThemeNames
327 \brief the list of theme names exposed by the loaded \l Style.
328
329 This list always includes \c System, which follows the platform color
330 scheme. It also includes \c Light and \c Dark when the \l Style defines
331 those themes, together with any custom themes that the style author
332 defines. The list is empty when no style is loaded.
333*/
334
335/*!
336 \property QStyleKitStyle::customThemeNames
337 \brief the list of custom theme names defined by the loaded \l Style.
338
339 Unlike \l availableThemeNames, this list excludes \c System, \c Light,
340 and \c Dark, and contains only the themes that the style author
341 defines explicitly. The list is empty when no style is loaded.
342
343 \sa availableThemeNames, themeName
344*/
345
346static QQStyleKitReader::ControlType controlTypeForWidget(const QWidget *widget)
347{
348 if (!widget)
349 return QQStyleKitReader::Control;
350
351#if QT_CONFIG(pushbutton)
352 if (qobject_cast<const QPushButton *>(widget))
353 return QQStyleKitReader::Button;
354#endif
355#if QT_CONFIG(checkbox)
356 if (qobject_cast<const QCheckBox *>(widget))
357 return QQStyleKitReader::CheckBox;
358#endif
359#if QT_CONFIG(radiobutton)
360 if (qobject_cast<const QRadioButton *>(widget))
361 return QQStyleKitReader::RadioButton;
362#endif
363#if QT_CONFIG(combobox)
364 if (qobject_cast<const QComboBox *>(widget))
365 return QQStyleKitReader::ComboBox;
366#endif
367#if QT_CONFIG(slider)
368 if (qobject_cast<const QSlider *>(widget))
369 return QQStyleKitReader::Slider;
370#endif
371#if QT_CONFIG(scrollbar)
372 if (qobject_cast<const QScrollBar *>(widget))
373 return QQStyleKitReader::ScrollBar;
374#endif
375#if QT_CONFIG(spinbox)
376 if (qobject_cast<const QSpinBox *>(widget) || qobject_cast<const QDoubleSpinBox *>(widget))
377 return QQStyleKitReader::SpinBox;
378#endif
379#if QT_CONFIG(itemviews)
380 if (qobject_cast<const QAbstractItemView *>(widget))
381 return QQStyleKitReader::ItemDelegate;
382#endif
383#if QT_CONFIG(progressbar)
384 if (qobject_cast<const QProgressBar *>(widget))
385 return QQStyleKitReader::ProgressBar;
386#endif
387#if QT_CONFIG(lineedit)
388 if (qobject_cast<const QLineEdit *>(widget))
389 return QQStyleKitReader::TextField;
390#endif
391#if QT_CONFIG(textedit)
392 if (qobject_cast<const QTextEdit *>(widget) || qobject_cast<const QPlainTextEdit *>(widget))
393 return QQStyleKitReader::TextArea;
394#endif
395#if QT_CONFIG(tabbar)
396 if (qobject_cast<const QTabBar *>(widget))
397 return QQStyleKitReader::TabBar;
398#endif
399#if QT_CONFIG(tabwidget)
400 if (qobject_cast<const QTabWidget *>(widget))
401 return QQStyleKitReader::Page;
402#endif
403#if QT_CONFIG(toolbar)
404 if (qobject_cast<const QToolBar *>(widget))
405 return QQStyleKitReader::ToolBar;
406#endif
407#if QT_CONFIG(toolbutton)
408 if (qobject_cast<const QToolButton *>(widget))
409 return QQStyleKitReader::ToolButton;
410#endif
411#if QT_CONFIG(groupbox)
412 if (qobject_cast<const QGroupBox *>(widget))
413 return QQStyleKitReader::GroupBox;
414#endif
415#if QT_CONFIG(menu)
416 if (qobject_cast<const QMenuBar *>(widget))
417 return QQStyleKitReader::MenuBar;
418 if (qobject_cast<const QMenu *>(widget))
419 return QQStyleKitReader::Menu;
420#endif
421#if QT_CONFIG(tooltip)
422 if (widget->inherits("QTipLabel"))
423 return QQStyleKitReader::ToolTip;
424#endif
425 if (widget->windowType() == Qt::Popup)
426 return QQStyleKitReader::Popup;
427 if (widget->windowType() == Qt::Dialog)
428 return QQStyleKitReader::Dialog;
429 if (widget->windowType() == Qt::Window)
430 return QQStyleKitReader::ApplicationWindow;
431#ifndef QT_NO_FRAME
432 if (qobject_cast<const QFrame *>(widget))
433 return QQStyleKitReader::Frame;
434#endif
435#if QT_CONFIG(dial)
436 if (qobject_cast<const QDial *>(widget))
437 return QQStyleKitReader::Dial;
438#endif
439 return QQStyleKitReader::Control;
440}
441
442#if QT_CONFIG(itemviews)
443static QQStyleKitReader::ControlType itemViewControlType(const QStyleOption *opt)
444{
445 const auto *itemViewOption = qstyleoption_cast<const QStyleOptionViewItem *>(opt);
446 return itemViewOption && (itemViewOption->features & QStyleOptionViewItem::HasCheckIndicator)
447 ? QQStyleKitReader::ControlType::CheckDelegate
448 : QQStyleKitReader::ControlType::ItemDelegate;
449}
450#endif
451
452// Some widgets (like QAbstractScrollArea) paint on a child widget (the viewport)
453// instead of on themselves. This function returns the widget that is actually painted on,
454// which is the one that should be updated when the style values change.
455static QWidget *paintTarget(const QWidget *widget)
456{
457#if QT_CONFIG(scrollarea)
458 if (const auto *area = qobject_cast<const QAbstractScrollArea *>(widget))
459 return area->viewport();
460#endif
461 return const_cast<QWidget *>(widget);
462}
463
464// Returns true for widgets that draw themselves using their widget font and
465// palette directly, bypassing the style's drawControl path.
466static bool isSelfPaintingWidget(const QWidget *widget)
467{
468 return false
469#if QT_CONFIG(label)
470 || qobject_cast<const QLabel *>(widget)
471#endif
472#if QT_CONFIG(textedit)
473 || qobject_cast<const QTextEdit *>(widget)
474 || qobject_cast<const QPlainTextEdit *>(widget)
475#endif
476#if QT_CONFIG(lineedit)
477 || qobject_cast<const QLineEdit *>(widget)
478#endif
479 ;
480}
481
482static QWidget *managedViewport(QWidget *widget)
483{
484#if QT_CONFIG(textedit)
485 if (auto *textEdit = qobject_cast<QTextEdit *>(widget))
486 return textEdit->viewport();
487 if (auto *plainTextEdit = qobject_cast<QPlainTextEdit *>(widget))
488 return plainTextEdit->viewport();
489#endif
490#if QT_CONFIG(itemviews) && QT_CONFIG(combobox)
491 if (auto *view = qobject_cast<QAbstractItemView *>(widget)) {
492 if (auto *p = view->parentWidget(); p && p->inherits("QComboBoxPrivateContainer"))
493 return view->viewport();
494 }
495#endif
496 return nullptr;
497}
498
499static uint resolvedAlignment(uint raw, Qt::Alignment hDefault, Qt::Alignment vDefault)
500{
501 uint result = 0;
502 const uint h = raw & Qt::AlignHorizontal_Mask;
503 const uint v = raw & Qt::AlignVertical_Mask;
504 result |= h ? h : uint(hDefault);
505 result |= v ? v : uint(vDefault);
506 return result;
507}
508
509static qreal resolvedWidth(const QQStyleKitDelegateProperties *element, qreal availableW)
510{
511 return qMax(0.0, element->fillWidth() ? availableW : element->width());
512}
513
514static qreal resolvedHeight(const QQStyleKitDelegateProperties *element, qreal availableH)
515{
516 return qMax(0.0, element->fillHeight() ? availableH : element->height());
517}
518
519
520static QPixmap iconPixmap(const QIcon &icon, const QSize &size, QStyle::State state,
521 const QPainter *p)
522{
523 if (icon.isNull())
524 return QPixmap();
525 const QIcon::Mode mode = state & QStyle::State_Enabled ? QIcon::Normal : QIcon::Disabled;
526 return icon.pixmap(size, p->device()->devicePixelRatio(), mode, QIcon::Off);
527}
528
529static QMargins elementMargins(const QQStyleKitDelegateProperties *element)
530{
531 using QtPrivate::qSaturateRound;
532 return QMargins(qSaturateRound(element->leftMargin()),
533 qSaturateRound(element->topMargin()),
534 qSaturateRound(element->rightMargin()),
535 qSaturateRound(element->bottomMargin()));
536}
537
538static QRectF alignedRectInContainer(const QRectF &container, const QSizeF &size,
539 uint alignment, const QMarginsF &padding,
540 const QMarginsF &margins)
541{
542 QPointF pos;
543
544 if (alignment & Qt::AlignLeft)
545 pos.setX(container.x() + padding.left() + margins.left());
546 else if (alignment & Qt::AlignHCenter)
547 pos.setX(container.x() + padding.left() + margins.left()
548 + (container.width() - padding.left() - padding.right() - margins.left()
549 - margins.right() - size.width()) / 2);
550 else // AlignRight
551 pos.setX(container.x() + container.width() - padding.right() - margins.right()
552 - size.width());
553
554 if (alignment & Qt::AlignTop)
555 pos.setY(container.y() + padding.top() + margins.top());
556 else if (alignment & Qt::AlignVCenter)
557 pos.setY(container.y() + padding.top() + margins.top()
558 + (container.height() - padding.top() - padding.bottom() - margins.top()
559 - margins.bottom() - size.height()) / 2);
560 else // AlignBottom
561 pos.setY(container.y() + container.height() - padding.bottom() - margins.bottom()
562 - size.height());
563
564 return QRectF(pos, size);
565}
566
567/*! \internal
568 Returns the rect of \a delegate inside \a container: sized from the width/height or fill
569 properties after deducting \a padding and the delegate's margins, then aligned (falling back
570 to \a hDefault and \a vDefault). Returns a null rect if \a delegate is null or not visible.
571*/
572static QRect delegateRect(const QQStyleKitDelegateProperties *delegate, const QRect &container,
573 Qt::Alignment hDefault, Qt::Alignment vDefault,
574 const QMargins &padding = QMargins())
575{
576 if (!delegate || !delegate->visible())
577 return QRect();
578 const qreal w = resolvedWidth(
579 delegate, container.width() - padding.left() - padding.right()
580 - delegate->leftMargin() - delegate->rightMargin());
581 const qreal h = resolvedHeight(
582 delegate, container.height() - padding.top() - padding.bottom()
583 - delegate->topMargin() - delegate->bottomMargin());
584 const uint alignment = resolvedAlignment(delegate->alignment(), hDefault, vDefault);
585
586 const QRectF r = alignedRectInContainer(
587 container, QSizeF(w, h), alignment, QMarginsF(padding),
588 QMarginsF(delegate->leftMargin(), delegate->topMargin(), delegate->rightMargin(),
589 delegate->bottomMargin()));
590
591 using QtPrivate::qSaturateRound;
592 const int left = qSaturateRound(r.left());
593 const int top = qSaturateRound(r.top());
594 return QRect(left, top, qSaturateRound(r.right()) - left, qSaturateRound(r.bottom()) - top);
595}
596
597/*! \internal
598 Applies \a element's rotation and scale to \a painter about the centre of \a box.
599 Returns \c false if the scale is 0 or if \a element is null, otherwise returns \c true.
600*/
601static bool applyDelegateTransform(QPainter *painter,
602 const QQStyleKitDelegateProperties *element,
603 const QRectF &box)
604{
605 if (!element)
606 return false;
607
608 const qreal scale = element->scale();
609 if (qFuzzyIsNull(scale))
610 return false;
611
612 const qreal rotation = element->rotation();
613 if (qFuzzyIsNull(rotation) && qFuzzyCompare(scale, 1.0))
614 return true;
615
616 const QPointF center = box.center();
617 painter->translate(center);
618 if (!qFuzzyIsNull(rotation))
619 painter->rotate(rotation);
620 if (!qFuzzyCompare(scale, 1.0))
621 painter->scale(scale, scale);
622 painter->translate(-center);
623 return true;
624}
625
626static void drawStyledItemImage(const QQStyleKitImageProperties *image, const QRectF &rect,
627 qreal opacity, QPainter *painter)
628{
629 if (!image || image->source().isEmpty() || image->color().alpha() <= 0)
630 return;
631
632 QString imageSource = image->source().toString();
633 if (imageSource.startsWith(QLatin1String("qrc:/")))
634 imageSource = imageSource.mid(3);
635 QUrl imageUrl(imageSource);
636 QString imagePath = imageUrl.isLocalFile() ? imageUrl.toLocalFile() : imageSource;
637 QPixmap pixmap(imagePath);
638 if (pixmap.isNull())
639 return;
640
641 if (image->color().isValid()) {
642 QImage coloredImage = pixmap.toImage();
643 QPainter imagePainter(&coloredImage);
644 imagePainter.setCompositionMode(QPainter::CompositionMode_SourceIn);
645 imagePainter.fillRect(coloredImage.rect(), image->color());
646 imagePainter.end();
647 pixmap = QPixmap::fromImage(coloredImage);
648 }
649 painter->setOpacity(opacity);
650 const QSizeF pixmapSize = pixmap.deviceIndependentSize();
651
652 switch (image->fillMode()) {
653 case QQuickImage::PreserveAspectFit: {
654 const QSize scaled = pixmapSize.scaled(rect.size(), Qt::KeepAspectRatio).toSize();
655 const QPointF topLeft(rect.x() + (rect.width() - scaled.width()) / 2.0,
656 rect.y() + (rect.height() - scaled.height()) / 2.0);
657 painter->drawPixmap(QRectF(topLeft, scaled), pixmap, QRectF(QPointF(0, 0), pixmapSize));
658 break;
659 }
660 case QQuickImage::PreserveAspectCrop: {
661 const QSize scaled = pixmapSize
662 .scaled(rect.size(), Qt::KeepAspectRatioByExpanding)
663 .toSize();
664 const QPointF topLeft(rect.x() + (rect.width() - scaled.width()) / 2.0,
665 rect.y() + (rect.height() - scaled.height()) / 2.0);
666 QPainterStateGuard stateGuard(painter);
667 painter->setClipRect(rect);
668 painter->drawPixmap(QRectF(topLeft, scaled), pixmap, QRectF(QPointF(0, 0), pixmapSize));
669 break;
670 }
671 // TODO: Support remaining fill modes
672 case QQuickImage::Stretch:
673 default:
674 painter->drawPixmap(rect, pixmap, QRectF(QPointF(0, 0), pixmapSize));
675 break;
676 }
677}
678
679static void drawStyledItemContents(const QQStyleKitDelegateProperties *props, const QRectF &rect,
680 QPainter *painter)
681{
682 if (!props || !props->visible() || props->opacity() <= 0 || !rect.isValid())
683 return;
684
685 QPainterStateGuard stateGuard(painter);
686 painter->setRenderHint(QPainter::Antialiasing, true);
687 if (props->clip())
688 painter->setClipping(true);
689
690 // opacity
691 const auto opacity = props->opacity();
692
693 // border
694 const auto *border = props->border();
695 auto borderWidth = 0;
696 auto inset = 0.0;
697 QColor borderColor;
698 if (border) {
699 borderWidth = border->width();
700 borderColor = border->color();
701 inset = borderWidth / 2.0;
702 }
703 if (borderWidth > 0 && borderColor.isValid() && borderColor.alpha() > 0) {
704 QPen pen(borderColor, borderWidth);
705 painter->setPen(pen);
706 } else {
707 painter->setPen(Qt::NoPen);
708 }
709
710 // radius
711 // TODO: support different radius for each corner
712 const qreal minDimension = qMin(rect.width(), rect.height());
713 const qreal xRadius = qMax(0.0, qMin(props->topLeftRadius() - inset, minDimension / 2.0));
714 const qreal yRadius = qMax(0.0, qMin(props->bottomLeftRadius() - inset, minDimension / 2.0));
715
716 QRectF adjustedRect = rect.adjusted(inset, inset, -inset, -inset);
717
718 // gradients/color
719 // TODO: support palette roles for colors and gradients
720 QColor color = props->color();
721 QBrush colorBrush(color);
722 painter->setBrush(colorBrush);
723 if (color.isValid()) {
724 painter->setOpacity(opacity);
725 painter->drawRoundedRect(adjustedRect, xRadius, yRadius, Qt::AbsoluteSize);
726 }
727 if (QQuickGradient *gradient = props->gradient()) {
728 QLinearGradient linearGradient(rect.topLeft(), rect.bottomLeft());
729 QQmlListProperty<QQuickGradientStop> stops = gradient->stops();
730 const int stopCount = stops.count(&stops);
731 for (int i = 0; i < stopCount; i++) {
732 QQuickGradientStop *stop = static_cast<QQuickGradientStop *>(stops.at(&stops, i));
733 linearGradient.setColorAt(stop->position(), stop->color());
734 }
735 QBrush gradientBrush(linearGradient);
736 painter->setBrush(gradientBrush);
737 painter->setOpacity(opacity);
738 painter->drawRoundedRect(adjustedRect, xRadius, yRadius, Qt::AbsoluteSize);
739 }
740
741 // image
742 drawStyledItemImage(props->image(), adjustedRect, opacity, painter);
743}
744
745static void drawStyledItemRect(const QQStyleKitDelegateProperties *props, const QRectF &rect,
746 QPainter *painter)
747{
748 if (!props || !props->visible() || props->opacity() <= 0 || !rect.isValid())
749 return;
750
751 QPainterStateGuard stateGuard(painter);
752 if (!applyDelegateTransform(painter, props, rect))
753 return;
754 drawStyledItemContents(props, rect, painter);
755}
756
757static void drawControlIndicator(const QQStyleKitDelegateProperties *indicator,
758 const QRectF &rect, QPainter *painter)
759{
760 if (!indicator || !indicator->visible() || indicator->opacity() <= 0 || !rect.isValid())
761 return;
762
763 // The foreground is a "child" of the indicator container so it
764 // inherits the indicator's transform. Apply it here and let the foreground stack its
765 // own on top.
766 QPainterStateGuard stateGuard(painter);
767 if (!applyDelegateTransform(painter, indicator, rect))
768 return;
769
770 // indicator (background)
771 QRectF indicatorRect = rect;
772 drawStyledItemContents(indicator, indicatorRect, painter);
773
774 const QQStyleKitDelegateProperties *foreground = nullptr;
775 if (auto *indicatorWithSubTypes =
776 qobject_cast<const QQStyleKitIndicatorWithSubTypes *>(indicator)) {
777 foreground = indicatorWithSubTypes->foreground();
778 } else if (auto *indicatorProps =
779 qobject_cast<const QQStyleKitIndicatorProperties *>(indicator)) {
780 foreground = indicatorProps->foreground();
781 } else {
782 return;
783 }
784 if (!foreground || !foreground->visible() || foreground->opacity() <= 0)
785 return;
786
787 // foreground
788 const uint foregroundAlign = resolvedAlignment(foreground->alignment(), Qt::AlignHCenter,
789 Qt::AlignVCenter);
790 const auto foregroundW = resolvedWidth(
791 foreground, indicatorRect.width() - foreground->leftMargin() - foreground->rightMargin());
792 const auto foregroundH = resolvedHeight(
793 foreground, indicatorRect.height() - foreground->topMargin() - foreground->bottomMargin());
794 const QRectF foregroundRect = alignedRectInContainer(
795 indicatorRect, QSizeF(foregroundW, foregroundH), foregroundAlign, QMarginsF(),
796 QMarginsF(foreground->leftMargin(), foreground->topMargin(), foreground->rightMargin(),
797 foreground->bottomMargin()));
798 drawStyledItemRect(foreground, foregroundRect, painter);
799}
800
801static void drawControlText(const QQStyleKitTextProperties *textProps, const QFont &font,
802 const QRect &rect, const QString &text, uint textFlags, QPainter *p,
803 Qt::Alignment defaultAlignment = Qt::AlignHCenter | Qt::AlignVCenter)
804{
805 uint flags = textFlags;
806 flags |= textProps
807 ? resolvedAlignment(textProps->alignment(), defaultAlignment & Qt::AlignHorizontal_Mask,
808 defaultAlignment & Qt::AlignVertical_Mask)
809 : uint(defaultAlignment);
810
811 const QFont oldFont = p->font();
812 p->setFont(font.resolve(oldFont));
813 p->setBrush(Qt::NoBrush);
814 p->setPen(textProps ? textProps->color() : QColor());
815 p->drawText(rect, flags, text, nullptr);
816}
817
818#if QT_CONFIG(dial)
819static qreal dialAngle(const QStyleOptionSlider *dial)
820{
821 const qreal range = dial->maximum - dial->minimum;
822 qreal position = range > 0 ? (dial->sliderPosition - dial->minimum) / range : 0;
823 if (!dial->upsideDown)
824 position = 1 - position;
825 const qreal start = dial->dialWrapping ? -180 : -150;
826 return start + position * -2 * start;
827}
828
829static QPointF dialHandleOffset(const QRectF &backgroundRect, const QQStyleKitDelegateProperties *handle)
830{
831 // mirrors Dial.qml
832 return QPointF(handle->leftMargin() - handle->rightMargin(),
833 -qMin(backgroundRect.width(), backgroundRect.height()) / 2 + handle->height() / 2
834 + handle->topMargin() - handle->bottomMargin());
835}
836#endif
837
838// Copied from qstylesheetstyle.cpp
839static const QWidget *containerWidget(const QWidget *w)
840{
841#if QT_CONFIG(lineedit)
842 if (qobject_cast<const QLineEdit *>(w)) {
843 // if the QLineEdit is an embeddedWidget, we need the real widget
844 QWidget *parent = w->parentWidget();
845 if (false
846# if QT_CONFIG(combobox)
847 || qobject_cast<const QComboBox *>(parent)
848# endif
849# if QT_CONFIG(spinbox)
850 || qobject_cast<const QAbstractSpinBox *>(parent)
851# endif
852 ) {
853 return parent;
854 }
855 }
856#endif
857
858#if QT_CONFIG(scrollarea)
859 if (const QAbstractScrollArea *sa =
860 qobject_cast<const QAbstractScrollArea *>(w->parentWidget())) {
861 if (sa->viewport() == w)
862 return w->parentWidget();
863 }
864#endif
865
866 return w;
867}
868
869QStyleKitStylePrivate::QStyleKitStylePrivate()
870 : QCommonStylePrivate()
871{
872}
873
874static QUrl urlFromStylePath(const QString &filePath)
875{
876 if (filePath.startsWith(QLatin1Char(':')))
877 return QUrl(QLatin1String("qrc") + filePath);
878 if (filePath.startsWith(QLatin1String("qrc:")) || filePath.startsWith(QLatin1String("file:")))
879 return QUrl(filePath);
880 return QUrl::fromLocalFile(filePath);
881}
882
883bool QStyleKitStylePrivate::loadStyle()
884{
885 Q_Q(QStyleKitStyle);
886 if (!qmlEngine)
887 qmlEngine = new QQmlEngine(q);
888
889 if (!qmlEngine) {
890 qWarning("QStyleKitStyle: No QML engine available to load style.");
891 return false;
892 }
893 const QUrl url = stylePath.isEmpty() ? QUrl() : urlFromStylePath(stylePath);
894 if (stylePath.isEmpty() || !url.isValid()) {
895 qWarning("QStyleKitStyle: No valid style path provided: %s", qPrintable(stylePath));
896 return false;
897 }
898 QQmlComponent component(qmlEngine, url);
899 if (component.isError()) {
900 qWarning("QStyleKitStyle: Failed to load style from %s: %s", qPrintable(stylePath),
901 qPrintable(component.errorString()));
902 return false;
903 }
904 // Avoid creating anything other than StyleKit Style objects
905 // by checking the metaobject of the root type before creating the object
906 QQmlComponentPrivate *componentPrivate = QQmlComponentPrivate::get(&component);
907 const auto compilationUnit = componentPrivate->compilationUnit();
908 const auto propertyCache = compilationUnit ? compilationUnit->rootPropertyCache() : nullptr;
909 const auto firstMetaObject = propertyCache ? propertyCache->firstCppMetaObject() : nullptr;
910 if (!firstMetaObject || !firstMetaObject->inherits(&QQStyleKitStyle::staticMetaObject)) {
911 qWarning("QStyleKitStyle: Failed to load style from %s: component is not a StyleKit Style.",
912 qPrintable(stylePath));
913 return false;
914 }
915 QQStyleKitStyle *styleObject = qobject_cast<QQStyleKitStyle *>(component.create());
916 if (!styleObject) {
917 qWarning("QStyleKitStyle: Failed to create style object from %s: "
918 "component is not a StyleKit style.",
919 qPrintable(stylePath));
920 return false;
921 }
922 const bool isReload = style != nullptr;
923 delete style;
924 style = styleObject;
925 style->setParent(q);
926
927 if (!isReload) {
928 QObject::connect(QGuiApplication::styleHints(), &QStyleHints::colorSchemeChanged, q,
929 [this]() {
930 if (style && style->themeName() == QLatin1String("System")) {
931 style->recreateTheme();
932 updateStyle();
933 }
934 });
935 }
936
937 if (style->loaded())
938 QQStyleKitReader::resetReadersForStyle(style);
939
940 return true;
941}
942
943/*! \internal
944 Creates and returns the empty fallback style used when no user
945 style is loaded.
946*/
947QQStyleKitStyle *QStyleKitStylePrivate::ensureDefaultStyle()
948{
949 if (defaultStyle)
950 return defaultStyle;
951
952 Q_Q(QStyleKitStyle);
953 if (!qmlEngine)
954 qmlEngine = new QQmlEngine(q);
955
956 QQmlComponent component(qmlEngine);
957 component.loadFromModule("Qt.labs.StyleKit", "Style");
958 if (component.isError()) {
959 qWarning("QStyleKitStyle: Failed to create default fallback style: %s",
960 qPrintable(component.errorString()));
961 return nullptr;
962 }
963 defaultStyle = qobject_cast<QQStyleKitStyle *>(component.create());
964 if (defaultStyle) {
965 defaultStyle->setParent(q);
966 qCDebug(lcStyleKit,
967 "No style set; using a default fallback style. "
968 "Set stylePath to load a StyleKit Style.");
969 }
970 return defaultStyle;
971}
972
973/*! \internal
974 Returns the user style if one is loaded, otherwise the default fallback
975 style
976*/
977QQStyleKitStyle *QStyleKitStylePrivate::effectiveStyle() const
978{
979 return style ? style : defaultStyle;
980}
981
982void QStyleKitStylePrivate::updateStyle()
983{
984 clearMetricsCache();
985
986 QQStyleKitStyle *effective = effectiveStyle();
987
988 if (sharedReader && sharedReader->style() != effective)
989 sharedReader->setExplicitStyle(effective);
990
991 if (subElementReader && subElementReader->style() != effective)
992 subElementReader->setExplicitStyle(effective);
993
994 clearAllSubElements();
995
996 for (auto *wr : std::as_const(widgetReaders)) {
997 if (wr->style() != effective)
998 wr->setExplicitStyle(effective);
999 }
1000
1001 if (!QWidgetPrivate::allWidgets)
1002 return;
1003
1004 for (auto *widget : std::as_const(*QWidgetPrivate::allWidgets)) {
1005 if (customFontWidgets.contains(widget))
1006 unsetStyleFont(widget);
1007 refreshStyleFont(widget);
1008 if (customPaletteWidgets.contains(widget))
1009 unsetStylePalette(widget);
1010 refreshStylePalette(widget);
1011 refreshStyleMinimumSize(widget);
1012 }
1013
1014 QEvent styleChange(QEvent::StyleChange);
1015 for (auto *widget : std::as_const(*QWidgetPrivate::allWidgets)) {
1016 QApplication::sendEvent(widget, &styleChange);
1017 widget->update();
1018 }
1019}
1020
1021void QStyleKitStylePrivate::refreshStyleMinimumSize(QWidget *widget)
1022{
1023 // QDial::sizeHint() is fixed and never asks the style, so enforce
1024 // the minimum size from the StyleKit style.
1025#if QT_CONFIG(dial)
1026 if (!qobject_cast<QDial *>(widget))
1027 return;
1028 const auto resolved = resolveLayout(QQStyleKitReader::ControlType::Dial, QStyle::State_Enabled);
1029 if (!resolved.isValid())
1030 return;
1031 const auto &m = *resolved.metrics;
1032 const QSize styleSize(m.bgImplicitSize.width() + m.margins.left() + m.margins.right(),
1033 m.bgImplicitSize.height() + m.margins.top() + m.margins.bottom());
1034
1035 auto it = customMinimumSizeWidgets.find(widget);
1036 if (it == customMinimumSizeWidgets.end()) {
1037 it = customMinimumSizeWidgets.insert(widget, widget->minimumSize());
1038 QObject::connect(widget, &QObject::destroyed, widget,
1039 [this, widget]() { customMinimumSizeWidgets.remove(widget); });
1040 }
1041 widget->setMinimumSize(it.value().expandedTo(styleSize));
1042#else
1043 Q_UNUSED(widget);
1044#endif
1045}
1046
1047void QStyleKitStylePrivate::unsetStyleMinimumSize(QWidget *widget)
1048{
1049 const auto it = customMinimumSizeWidgets.constFind(widget);
1050 if (it == customMinimumSizeWidgets.cend())
1051 return;
1052 const QSize original = it.value();
1053 customMinimumSizeWidgets.erase(it);
1054 widget->setMinimumSize(original);
1055}
1056
1057void QStyleKitStylePrivate::setStyleAutoFill(QWidget *widget)
1058{
1059 // Disable the viewport's autoFillBackground
1060 // so the styled background shows through
1061 if (QWidget *vp = managedViewport(widget); vp && vp->autoFillBackground()) {
1062 vp->setAutoFillBackground(false);
1063 autoFillDisabledWidgets.insert(widget);
1064 }
1065}
1066
1067void QStyleKitStylePrivate::unsetStyleAutoFill(QWidget *widget)
1068{
1069 if (!autoFillDisabledWidgets.remove(widget))
1070 return;
1071 if (QWidget *vp = managedViewport(widget))
1072 vp->setAutoFillBackground(true);
1073}
1074
1075void QStyleKitStylePrivate::setStyleTranslucency(QWidget *widget)
1076{
1077 const bool isPopup = false
1078#if QT_CONFIG(menu)
1079 || qobject_cast<QMenu *>(widget)
1080#endif
1081#if QT_CONFIG(combobox)
1082 || widget->inherits("QComboBoxPrivateContainer")
1083#endif
1084#if QT_CONFIG(tooltip)
1085 || widget->inherits("QTipLabel")
1086#endif
1087 ;
1088 if (!isPopup || widget->testAttribute(Qt::WA_TranslucentBackground))
1089 return;
1090 // Enable translucency for popups so that we can draw rounded corners
1091 widget->setAttribute(Qt::WA_TranslucentBackground, true);
1092 widget->setWindowFlag(Qt::FramelessWindowHint, true);
1093 translucentWidgets.insert(widget);
1094}
1095
1096void QStyleKitStylePrivate::unsetStyleTranslucency(QWidget *widget)
1097{
1098 if (!translucentWidgets.remove(widget))
1099 return;
1100 widget->setAttribute(Qt::WA_TranslucentBackground, false);
1101 widget->setWindowFlag(Qt::FramelessWindowHint, false);
1102}
1103
1104// Follow the approach in qstylesheetstyle.cpp
1105void QStyleKitStylePrivate::unsetStyleFont(QWidget *widget)
1106{
1107 auto it = customFontWidgets.find(widget);
1108 if (it == customFontWidgets.end())
1109 return;
1110
1111 auto customFont = std::move(*it);
1112 customFontWidgets.erase(it);
1113 widget->setFont(std::move(customFont).reverted(QWidgetPrivate::get(widget)->localFont()));
1114}
1115
1116void QStyleKitStylePrivate::setStyleFont(QWidget *widget, const QFont &styleFont)
1117{
1118 if (!effectiveStyle() || !widget)
1119 return;
1120
1121 const auto styleMask = styleFont.resolveMask();
1122 auto it = customFontWidgets.find(widget);
1123
1124 if (it == customFontWidgets.end()) {
1125 if (styleMask == 0)
1126 return;
1127 it = customFontWidgets.insert(widget, { QWidgetPrivate::get(widget)->localFont(), 0 });
1128 QObject::connect(widget, &QObject::destroyed, widget,
1129 [this, widget]() { customFontWidgets.remove(widget); });
1130 }
1131
1132 it->resolveMask = styleMask;
1133
1134 const QFont &baseline = it->oldWidgetValue;
1135 QFont merged = styleFont.resolve(baseline);
1136 merged.setResolveMask(baseline.resolveMask() | styleMask);
1137 widget->setFont(merged);
1138}
1139
1140void QStyleKitStylePrivate::refreshStyleFont(QWidget *widget)
1141{
1142 if (!effectiveStyle() || !widget)
1143 return;
1144
1145 const QWidget *targetWidget = containerWidget(widget);
1146 QQStyleKitReader::ControlType controlType = controlTypeForWidget(targetWidget);
1147
1148 auto *shared = ensureSharedReader();
1149 if (!shared)
1150 return;
1151
1152 QStyleOption opt;
1153 opt.initFrom(targetWidget);
1154 const QQSK::State currentState = resolvedStateFor(controlType, opt.state, targetWidget);
1155
1156 shared->setControlTypeAndState(controlType, currentState, false);
1157 setStyleFont(widget, shared->font());
1158}
1159
1160void QStyleKitStylePrivate::unsetStylePalette(QWidget *widget)
1161{
1162 auto it = customPaletteWidgets.find(widget);
1163 if (it == customPaletteWidgets.end())
1164 return;
1165
1166 auto customPalette = std::move(*it);
1167 customPaletteWidgets.erase(it);
1168 widget->setPalette(std::move(customPalette).reverted(widget->palette()));
1169}
1170
1171void QStyleKitStylePrivate::setStylePalette(QWidget *widget, const QPalette &stylePalette) const
1172{
1173 if (!effectiveStyle() || !widget)
1174 return;
1175
1176 const quint64 styleMask = stylePalette.resolveMask();
1177 if (styleMask == 0)
1178 return;
1179
1180 if (!customPaletteWidgets.contains(widget)) {
1181 customPaletteWidgets.insert(widget, { widget->palette(), 0 });
1182 QObject::connect(widget, &QObject::destroyed, widget,
1183 [this, widget]() { customPaletteWidgets.remove(widget); });
1184 }
1185
1186 customPaletteWidgets[widget].resolveMask |= styleMask;
1187 QPalette merged = stylePalette.resolve(widget->palette());
1188 merged.setResolveMask(widget->palette().resolveMask() | styleMask);
1189 widget->setPalette(merged);
1190}
1191
1192// For widgets that partially or fully draw themselves (instead of delegating to the style),
1193// using palette roles, we need to push the style colors to those roles
1194void QStyleKitStylePrivate::refreshStylePalette(QWidget *widget)
1195{
1196 if (!effectiveStyle() || !widget)
1197 return;
1198
1199 const bool isWindow = widget->isWindow();
1200 const bool isPaletteManaged = isSelfPaintingWidget(widget) || isWindow;
1201 if (!isPaletteManaged)
1202 return;
1203
1204 const QWidget *targetWidget = containerWidget(widget);
1205 QQStyleKitReader::ControlType controlType = controlTypeForWidget(targetWidget);
1206
1207 auto *shared = ensureSharedReader();
1208 if (!shared)
1209 return;
1210
1211 QStyleOption opt;
1212 opt.initFrom(targetWidget);
1213 const QQSK::State currentState = resolvedStateFor(controlType, opt.state, targetWidget);
1214
1215 QPalette stylePalette;
1216 shared->setControlTypeAndState(controlType, currentState, false);
1217 if (isWindow) {
1218 // Tooltips draw their text using QPalette::ToolTipText role
1219 if (controlType == QQStyleKitReader::ControlType::ToolTip) {
1220 if (const auto *text = shared->global()->text();
1221 text && text->isDefined(QQSK::Property::Color)) {
1222 stylePalette.setColor(QPalette::ToolTipText, text->color());
1223 }
1224 } else {
1225 // Windows draw their own background using the QPalette::Window role
1226 if (const auto *bg = shared->global()->background();
1227 bg && bg->isDefined(QQSK::Property::Color)) {
1228 stylePalette.setColor(QPalette::Window, bg->color());
1229 }
1230 shared->setControlTypeAndState(controlType, QQSK::StateFlag::Disabled, false);
1231 if (const auto *dbg = shared->global()->background();
1232 dbg && dbg->isDefined(QQSK::Property::Color)) {
1233 stylePalette.setColor(QPalette::Disabled, QPalette::Window, dbg->color());
1234 }
1235 }
1236 } else {
1237 // The remaining text-based widgets use the QPalette::Text/WindowText roles for their
1238 // foreground color
1239 shared->setControlTypeAndState(controlType, currentState, false);
1240 if (const auto *text = shared->global()->text();
1241 text && text->isDefined(QQSK::Property::Color)) {
1242 stylePalette.setColor(QPalette::Text, text->color());
1243 stylePalette.setColor(QPalette::WindowText, text->color());
1244 }
1245 shared->setControlTypeAndState(controlType, QQSK::StateFlag::Disabled, false);
1246 if (const auto *dt = shared->global()->text();
1247 dt && dt->isDefined(QQSK::Property::Color)) {
1248 stylePalette.setColor(QPalette::Disabled, QPalette::Text, dt->color());
1249 stylePalette.setColor(QPalette::Disabled, QPalette::WindowText, dt->color());
1250 }
1251 }
1252
1253 setStylePalette(widget, stylePalette);
1254}
1255
1256/*! \internal
1257 Returns a reader for the given widget, creating and caching it if needed.
1258*/
1259QQStyleKitReader *QStyleKitStylePrivate::readerForWidget(const QWidget *widget) const
1260{
1261 Q_Q(const QStyleKitStyle);
1262 QQStyleKitStyle *effective = effectiveStyle();
1263 if (!effective || !widget)
1264 return nullptr;
1265
1266 if (auto it = widgetReaders.find(widget); it != widgetReaders.end())
1267 return *it;
1268
1269 auto *widgetReader = new QQStyleKitReader(const_cast<QStyleKitStyle *>(q));
1270 widgetReader->setExplicitStyle(effective);
1271 widgetReader->setTarget(paintTarget(widget));
1272 widgetReader->setControlType(controlTypeForWidget(widget));
1273 widgetReader->setCompleted(true);
1274 widgetReaders.insert(widget, widgetReader);
1275 QObjectPrivate::connect(widget, &QObject::destroyed, this,
1276 &QStyleKitStylePrivate::onWidgetDestroyed, Qt::UniqueConnection);
1277 return widgetReader;
1278}
1279
1280void QStyleKitStylePrivate::cleanupWidgetReader(const QWidget *widget) const
1281{
1282 if (auto *reader = widgetReaders.take(widget))
1283 reader->deleteLater();
1284 cleanupSubElements(widget);
1285}
1286
1287void QStyleKitStylePrivate::onWidgetDestroyed(QObject *w) const
1288{
1289 cleanupWidgetReader(static_cast<QWidget *>(w));
1290}
1291
1292/*! \internal
1293 Returns the key identifying the sub-element (item-view cell, menu item or
1294 menubar item) that \a opt refers to, or an invalid key if the option does
1295 not identify one.
1296*/
1297QStyleKitStylePrivate::SubElementKey
1298QStyleKitStylePrivate::subElementKeyForOption(const QStyleOption *opt, const QWidget *widget)
1299{
1300 SubElementKey key;
1301 if (!widget)
1302 return key;
1303
1304#if QT_CONFIG(itemviews)
1305 if (const auto *viewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
1306 const QModelIndex &idx = viewOpt->index;
1307 if (!idx.isValid())
1308 return key;
1309 key.widget = widget;
1310 key.id = SubElementKey::ItemViewCell{ idx.model(), idx.internalId(), idx.row(),
1311 idx.column() };
1312 return key;
1313 }
1314#endif
1315#if QT_CONFIG(menu)
1316 if (const auto *menuOpt = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
1317 if (menuOpt->menuItemType == QStyleOptionMenuItem::Separator)
1318 return key;
1319 QAction *action = nullptr;
1320 if (const auto *menu = qobject_cast<const QMenu *>(widget))
1321 action = menu->actionAt(menuOpt->rect.center());
1322 else if (const auto *menuBar = qobject_cast<const QMenuBar *>(widget))
1323 action = menuBar->actionAt(menuOpt->rect.center());
1324 if (action) {
1325 key.widget = widget;
1326 key.id = SubElementKey::Action{ action };
1327 }
1328 return key;
1329 }
1330#endif
1331#if QT_CONFIG(tabbar)
1332 if (const auto *tabOpt = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
1333 if (tabOpt->tabIndex < 0)
1334 return key;
1335 key.widget = widget;
1336 key.id = SubElementKey::Tab{ tabOpt->tabIndex };
1337 return key;
1338 }
1339#endif
1340 return key;
1341}
1342
1343/*! \internal
1344 Creates and returns a transitions-enabled reader for the given sub-element
1345 that animates from \a fromState to \a toState
1346
1347*/
1348QQStyleKitReader *QStyleKitStylePrivate::startSubElementTransition(
1349 const SubElementKey &key, QQStyleKitReader::ControlType type, QQSK::State fromState,
1350 QQSK::State toState, QQuickTransition *transition) const
1351{
1352 Q_Q(const QStyleKitStyle);
1353 QQStyleKitStyle *effective = effectiveStyle();
1354 if (!effective)
1355 return nullptr;
1356
1357 // Reclaim finished readers. running() is per (shared) transition object, so
1358 // it turns false only once no instance of that transition animates anywhere
1359 for (auto it = subElementAnimationReaders.begin(); it != subElementAnimationReaders.end();) {
1360 const QQuickTransition *t = it.value()->transition();
1361 if (!t || !t->running()) {
1362 it.value()->deleteLater();
1363 it = subElementAnimationReaders.erase(it);
1364 } else {
1365 ++it;
1366 }
1367 }
1368
1369
1370 if (subElementAnimationReaders.size() >= kMaxSubElementAnimationReaders) {
1371 const auto it = subElementAnimationReaders.begin();
1372 if (const QWidget *widget = it.key().widget)
1373 paintTarget(widget)->update(); // snap to end state
1374 it.value()->deleteLater();
1375 subElementAnimationReaders.erase(it);
1376 }
1377
1378 auto *reader = new QQStyleKitReader(const_cast<QStyleKitStyle *>(q));
1379 reader->setExplicitStyle(effective);
1380 reader->setTarget(paintTarget(key.widget));
1381 // just stores the fromState, doesn't start the animation yet
1382 reader->setControlTypeAndState(type, fromState);
1383 reader->setCompleted(true);
1384 // As delegates are created lazily, a fresh reader has none,
1385 // so we need to create them now so delegates can already start animating changes
1386 // Only create delegates actually used by subelements, ie: background, indicators
1387 reader->background();
1388 auto *indicator = reader->indicator();
1389 indicator->first()->foreground();
1390 indicator->second()->foreground();
1391 // Start the transition to the new state
1392 reader->setControlTypeAndState(type, toState);
1393 if (!transition || !transition->running()) {
1394 reader->deleteLater();
1395 return nullptr;
1396 }
1397 subElementAnimationReaders.insert(key, reader);
1398 return reader;
1399}
1400
1401/*! \internal
1402 Drops all sub-element state tracking and animation readers for \a widget.
1403*/
1404void QStyleKitStylePrivate::cleanupSubElements(const QWidget *widget) const
1405{
1406 for (auto it = subElementStates.begin(); it != subElementStates.end();) {
1407 if (it.key().widget == widget)
1408 it = subElementStates.erase(it);
1409 else
1410 ++it;
1411 }
1412 for (auto it = subElementAnimationReaders.begin(); it != subElementAnimationReaders.end();) {
1413 if (it.key().widget == widget) {
1414 it.value()->deleteLater();
1415 it = subElementAnimationReaders.erase(it);
1416 } else {
1417 ++it;
1418 }
1419 }
1420}
1421
1422/*! \internal
1423 Drops all sub-element state tracking and animation readers.
1424*/
1425void QStyleKitStylePrivate::clearAllSubElements() const
1426{
1427 subElementStates.clear();
1428 for (QQStyleKitReader *reader : std::as_const(subElementAnimationReaders))
1429 reader->deleteLater();
1430 subElementAnimationReaders.clear();
1431}
1432
1433/*! \internal
1434 Resolves the given QStyle::State into a QQSK::State based on the mapping of
1435 state flags for the given control type.
1436*/
1437QQSK::State QStyleKitStylePrivate::resolvedStateFor(QQStyleKitReader::ControlType type,
1438 QStyle::State state,
1439 const QWidget *widget) const
1440{
1441 QQSK::State flags;
1442 flags.setFlag(QQSK::StateFlag::Hovered, (state & QStyle::State_MouseOver));
1443 flags.setFlag(QQSK::StateFlag::Pressed, state & QStyle::State_Sunken);
1444 flags.setFlag(QQSK::StateFlag::Checked, state & QStyle::State_On);
1445 flags.setFlag(QQSK::StateFlag::Focused, state & QStyle::State_HasFocus);
1446 flags.setFlag(QQSK::StateFlag::Highlighted, state & QStyle::State_Selected);
1447
1448 bool hasOrientation = false;
1449 switch (type) {
1450 case QQStyleKitReader::ProgressBar:
1451 case QQStyleKitReader::ScrollBar:
1452 case QQStyleKitReader::ScrollIndicator:
1453 case QQStyleKitReader::Slider:
1454 case QQStyleKitReader::ToolBar:
1455 case QQStyleKitReader::ToolSeparator:
1456 hasOrientation = true;
1457 break;
1458 default:
1459 break;
1460 }
1461 if (hasOrientation)
1462 flags.setFlag(QQSK::StateFlag::Vertical, !(state & QStyle::State_Horizontal));
1463 // Some widgets don't set State_Enabled in their
1464 // style option even when the widget is enabled.
1465 // Fall back to widget->isEnabled() in that case
1466 const bool enabled = (state & QStyle::State_Enabled) || (widget && widget->isEnabled());
1467 flags.setFlag(QQSK::StateFlag::Disabled, !enabled);
1468
1469 // ComboBox uses QStyle::State_On to indicate the popup is open, which is
1470 // not a "checked" semantic.
1471 if (type == QQStyleKitReader::ControlType::ComboBox)
1472 flags.setFlag(QQSK::StateFlag::Checked, false);
1473
1474 // Popup has no hover state in the Controls style
1475 if (type == QQStyleKitReader::ControlType::Popup)
1476 flags.setFlag(QQSK::StateFlag::Hovered, false);
1477
1478 // QTabBar sets State_Selected (not State_On) on the current tab
1479 if (type == QQStyleKitReader::ControlType::TabButton) {
1480 flags.setFlag(QQSK::StateFlag::Checked, state & QStyle::State_Selected);
1481 flags.setFlag(QQSK::StateFlag::Highlighted, false);
1482 }
1483
1484 return flags;
1485}
1486
1487/*! \internal
1488 Returns the ControlMetrics for the given control type and state,
1489 reading from the style if needed and caching the result.
1490*/
1491const QStyleKitStylePrivate::ControlMetrics &
1492QStyleKitStylePrivate::metricsFor(QQStyleKitReader::ControlType type, QQSK::State state) const
1493{
1494 if (auto it = metricsCache.find({ type, state }); it != metricsCache.end())
1495 return *it;
1496
1497 auto *reader = ensureSharedReader();
1498 Q_ASSERT(reader);
1499 reader->setControlTypeAndState(type, state, false);
1500 return *metricsCache.insert({ type, state }, metricsForReader(reader));
1501}
1502
1503/*! \internal
1504 Resolves the properties for the given widget, control type and state,
1505 and returns them as a QQStyleKitResolved.
1506*/
1507QStyleKitStylePrivate::QQStyleKitResolved
1508QStyleKitStylePrivate::resolve(const QWidget *w, QQStyleKitReader::ControlType type,
1509 QStyle::State state) const
1510{
1511 QQStyleKitResolved out;
1512 out.widget = w;
1513
1514 auto *reader = readerForWidget(w);
1515 if (!reader)
1516 return out;
1517
1518 const QQSK::State resolvedState = resolvedStateFor(type, state, w);
1519 reader->setControlTypeAndState(type, resolvedState);
1520
1521 out.reader = reader;
1522 out.metrics = &metricsFor(type, resolvedState);
1523 return out;
1524}
1525
1526/*! \internal
1527 Resolves the properties for a sub-element of \a w (an item-view item, menu/
1528 menuBar item), and returns them as a QQStyleKitResolved.
1529
1530 Sub-elements in a steady-state use the shared, transitions-disabled
1531 subElementReader. When a sub-element is observed to change state and
1532 the style defines a transition for the new state, a transient per-item
1533 reader is created to run that transition
1534
1535 Pass \a track = false for synthetic resolves that should not register state changes
1536 or retarget a running animation.
1537*/
1538QStyleKitStylePrivate::QQStyleKitResolved
1539QStyleKitStylePrivate::resolveSubElement(const QWidget *w, const QStyleOption *opt,
1540 QQStyleKitReader::ControlType type, QStyle::State state,
1541 bool track) const
1542{
1543 QQStyleKitResolved out;
1544 out.widget = w;
1545
1546 auto *steadyReader = ensureSubElementReader();
1547 if (!steadyReader)
1548 return out;
1549
1550 const QQSK::State newState = resolvedStateFor(type, state, w);
1551 const SubElementKey key = subElementKeyForOption(opt, w);
1552
1553 QQStyleKitReader *reader = nullptr;
1554 if (track && key.isValid()) {
1555 QQStyleKitReader *animReader = subElementAnimationReaders.value(key);
1556 const auto it = subElementStates.constFind(key);
1557 const bool seen = it != subElementStates.cend();
1558
1559 // Fallback to a reasonable base state to transition from by stripping the
1560 // interactive/pointer-driven flags from the new state.
1561 constexpr QQSK::State InteractiveStates = QQSK::State(QQSK::StateFlag::Hovered)
1562 | QQSK::StateFlag::Pressed | QQSK::StateFlag::Checked
1563 | QQSK::StateFlag::Focused | QQSK::StateFlag::Highlighted;
1564 const auto baseState = newState & ~InteractiveStates;
1565 const QQSK::State prevState = seen ? *it : baseState;
1566 if (prevState != newState) {
1567 if (animReader) {
1568 // State changed before transition finished
1569 // Retarget to new state, the transition continues from the current interpolated
1570 // values
1571 animReader->setControlTypeAndState(type, newState);
1572 } else {
1573 // Only pointer-driven states should animate
1574 // If an item first comes into view checked/highlighted, etc.,
1575 // it should not animate
1576 const bool shouldAnimate = seen || newState.testFlag(QQSK::StateFlag::Hovered)
1577 || newState.testFlag(QQSK::StateFlag::Pressed);
1578 if (shouldAnimate) {
1579 steadyReader->setControlTypeAndState(type, newState);
1580 if (QQuickTransition *transition = steadyReader->transition())
1581 animReader = startSubElementTransition(key, type, prevState,
1582 newState, transition);
1583 }
1584 }
1585 }
1586 if (!seen || prevState != newState) {
1587 QObjectPrivate::connect(w, &QObject::destroyed, this,
1588 &QStyleKitStylePrivate::onWidgetDestroyed,
1589 Qt::UniqueConnection);
1590 if (subElementStates.size() >= kMaxSubElementStates)
1591 subElementStates.clear();
1592 subElementStates.insert(key, newState);
1593 }
1594 reader = animReader;
1595 }
1596
1597 if (!reader)
1598 reader = steadyReader;
1599 reader->setControlTypeAndState(type, newState);
1600
1601 out.reader = reader;
1602 out.metrics = &metricsFor(type, newState);
1603 return out;
1604}
1605
1606const QQStyleKitTextProperties *QStyleKitStylePrivate::QQStyleKitResolved::text() const
1607{
1608 return reader ? reader->text() : nullptr;
1609}
1610
1611const QQStyleKitDelegateProperties *QStyleKitStylePrivate::QQStyleKitResolved::background() const
1612{
1613 return reader ? reader->background() : nullptr;
1614}
1615
1616const QQStyleKitHandleProperties *QStyleKitStylePrivate::QQStyleKitResolved::handle() const
1617{
1618 return reader ? reader->handle() : nullptr;
1619}
1620
1621const QQStyleKitIndicatorWithSubTypes *QStyleKitStylePrivate::QQStyleKitResolved::indicator() const
1622{
1623 return reader ? reader->indicator() : nullptr;
1624}
1625
1626QFont QStyleKitStylePrivate::QQStyleKitResolved::font() const
1627{
1628 return reader ? reader->font() : QFont();
1629}
1630
1631void QStyleKitStylePrivate::QQStyleKitResolved::drawBackground(const QRectF &rect,
1632 QPainter *p) const
1633{
1634 drawStyledItemRect(background(), rect, p);
1635}
1636
1637void QStyleKitStylePrivate::QQStyleKitResolved::drawIndicator(const QRectF &rect,
1638 QPainter *p) const
1639{
1640 drawControlIndicator(indicator(), rect, p);
1641}
1642
1643void QStyleKitStylePrivate::QQStyleKitResolved::drawSubIndicator(bool first, const QRectF &rect,
1644 QPainter *p) const
1645{
1646 const auto *ind = indicator();
1647 if (ind)
1648 drawControlIndicator(first ? ind->first() : ind->second(), rect, p);
1649}
1650
1651void QStyleKitStylePrivate::QQStyleKitResolved::drawHandle(const QRectF &rect, QPainter *p) const
1652{
1653 drawStyledItemRect(handle(), rect, p);
1654}
1655
1656void QStyleKitStylePrivate::QQStyleKitResolved::drawText(const QRect &rect, const QString &text,
1657 uint textFlags, QPainter *p,
1658 Qt::Alignment defaultAlignment) const
1659{
1660 drawControlText(this->text(), font(), rect, text, textFlags, p, defaultAlignment);
1661}
1662
1663/*! \internal
1664 Draws \a icon and \a str in \a rect as one group aligned by the text alignment, with the
1665 text beside or under the icon.
1666*/
1667void QStyleKitStylePrivate::QQStyleKitResolved::drawLabel(const QRect &rect, const QString &str,
1668 const QIcon &icon, const QSize &iconSize,
1669 QStyle::State state, uint textFlags,
1670 Qt::LayoutDirection direction,
1671 QPainter *p,
1672 Qt::Alignment defaultAlignment,
1673 bool textUnderIcon) const
1674{
1675 const QPixmap pixmap = iconPixmap(icon, iconSize, state, p);
1676 if (pixmap.isNull()) {
1677 drawText(rect, str, textFlags, p, defaultAlignment);
1678 return;
1679 }
1680
1681 const auto *textProps = text();
1682 const auto alignment = Qt::Alignment(resolvedAlignment(
1683 textProps ? textProps->alignment() : 0u, defaultAlignment & Qt::AlignHorizontal_Mask,
1684 defaultAlignment & Qt::AlignVertical_Mask));
1685 const QSize pixmapSize = pixmap.deviceIndependentSize().toSize().boundedTo(rect.size());
1686 if (str.isEmpty()) {
1687 p->drawPixmap(QStyle::alignedRect(direction, alignment, pixmapSize, rect), pixmap);
1688 return;
1689 }
1690
1691 const int spacing = pixmapSize.isEmpty() ? 0 : metrics->spacing;
1692 QSize textSize = QFontMetrics(font().resolve(p->font())).size(textFlags, str);
1693 QSize labelSize;
1694 Qt::Alignment iconAlignment;
1695 Qt::Alignment textAlignment;
1696 if (textUnderIcon) {
1697 textSize = textSize.boundedTo(
1698 QSize(rect.width(), qMax(0, rect.height() - pixmapSize.height() - spacing)));
1699 labelSize = QSize(qMax(pixmapSize.width(), textSize.width()),
1700 pixmapSize.height() + spacing + textSize.height());
1701 iconAlignment = Qt::AlignHCenter | Qt::AlignTop;
1702 textAlignment = Qt::AlignHCenter | Qt::AlignBottom;
1703 } else {
1704 textSize = textSize.boundedTo(
1705 QSize(qMax(0, rect.width() - pixmapSize.width() - spacing), rect.height()));
1706 labelSize = QSize(pixmapSize.width() + spacing + textSize.width(),
1707 qMax(pixmapSize.height(), textSize.height()));
1708 iconAlignment = Qt::AlignLeft | Qt::AlignVCenter;
1709 textAlignment = Qt::AlignRight | Qt::AlignVCenter;
1710 }
1711 const QRect labelRect = QStyle::alignedRect(direction, alignment, labelSize, rect);
1712 p->drawPixmap(QStyle::alignedRect(direction, iconAlignment, pixmapSize, labelRect), pixmap);
1713 drawText(QStyle::alignedRect(direction, textAlignment, textSize, labelRect), str,
1714 textFlags, p, defaultAlignment);
1715}
1716
1717QQStyleKitReader *QStyleKitStylePrivate::ensureSharedReader() const
1718{
1719 if (sharedReader)
1720 return sharedReader;
1721
1722 Q_Q(const QStyleKitStyle);
1723 QQStyleKitStyle *effective = effectiveStyle();
1724 if (!effective)
1725 return nullptr;
1726 sharedReader = new QQStyleKitReader(const_cast<QStyleKitStyle *>(q));
1727 // Disable transitions since this reader is used for one-off metric reads in layout queries
1728 sharedReader->setTransitionsEnabled(false);
1729 sharedReader->setExplicitStyle(effective);
1730 sharedReader->setCompleted(true);
1731 return sharedReader;
1732}
1733
1734QQStyleKitReader *QStyleKitStylePrivate::ensureSubElementReader() const
1735{
1736 if (subElementReader)
1737 return subElementReader;
1738
1739 Q_Q(const QStyleKitStyle);
1740 QQStyleKitStyle *effective = effectiveStyle();
1741 if (!effective)
1742 return nullptr;
1743 subElementReader = new QQStyleKitReader(const_cast<QStyleKitStyle *>(q));
1744 // Disable transitions: this reader is retargeted across many sub-elements
1745 // per paint pass and must never animate between their states
1746 subElementReader->setTransitionsEnabled(false);
1747 subElementReader->setExplicitStyle(effective);
1748 subElementReader->setCompleted(true);
1749 return subElementReader;
1750}
1751
1752/*! \internal
1753 Resolves the properties for the given control type and state using the shared reader,
1754 which disables transitions and is used for layout queries, so that layout never depends
1755 on animation state.
1756*/
1757QStyleKitStylePrivate::QQStyleKitLayoutResolved
1758QStyleKitStylePrivate::resolveLayout(QQStyleKitReader::ControlType type, QStyle::State state) const
1759{
1760 QQStyleKitLayoutResolved out;
1761 auto *reader = ensureSharedReader();
1762 if (!reader)
1763 return out;
1764
1765 const QQSK::State resolvedState = resolvedStateFor(type, state);
1766 out.metrics = &metricsFor(type, resolvedState);
1767 // metricsFor() sets the sharedReader to (type, resolvedState) on cache miss.
1768 // On hit it didn't, so make sure staticProps / staticFont reflect the state
1769 // and type of the caller
1770 reader->setControlTypeAndState(type, resolvedState, false);
1771 out.staticProps = reader->global();
1772 out.staticFont = reader->font();
1773 return out;
1774}
1775
1776const QQStyleKitTextProperties *QStyleKitStylePrivate::QQStyleKitLayoutResolved::text() const
1777{
1778 return staticProps ? staticProps->text() : nullptr;
1779}
1780
1781const QQStyleKitDelegateProperties *
1782QStyleKitStylePrivate::QQStyleKitLayoutResolved::background() const
1783{
1784 return staticProps ? staticProps->background() : nullptr;
1785}
1786
1787const QQStyleKitHandleProperties *QStyleKitStylePrivate::QQStyleKitLayoutResolved::handle() const
1788{
1789 return staticProps ? staticProps->handle() : nullptr;
1790}
1791
1792const QQStyleKitIndicatorWithSubTypes *
1793QStyleKitStylePrivate::QQStyleKitLayoutResolved::indicator() const
1794{
1795 return staticProps ? staticProps->indicator() : nullptr;
1796}
1797
1798void QStyleKitStylePrivate::clearMetricsCache()
1799{
1800 metricsCache.clear();
1801}
1802
1803QStyleKitStylePrivate::ControlMetrics
1804QStyleKitStylePrivate::metricsForReader(QQStyleKitReader *reader) const
1805{
1806 Q_ASSERT(reader);
1807 using QtPrivate::qSaturateRound;
1808 const QQStyleKitControlProperties *props = reader->global();
1809 ControlMetrics metrics;
1810 metrics.bgImplicitSize = QSize(0, 0);
1811 metrics.textPadding = QMargins(0, 0, 0, 0);
1812 metrics.padding = QMargins(qSaturateRound(props->leftPadding()),
1813 qSaturateRound(props->topPadding()),
1814 qSaturateRound(props->rightPadding()),
1815 qSaturateRound(props->bottomPadding()));
1816 metrics.spacing = qSaturateRound(props->spacing());
1817 metrics.margins = QMargins(0, 0, 0, 0);
1818 metrics.indicatorImplicitSize = QSize(0, 0);
1819 metrics.indicatorMargins = QMargins(0, 0, 0, 0);
1820 const auto *background = props->background();
1821
1822 // Note: scale is deliberately absent here as it should not affect layout
1823 const auto elementSize = [](qreal w, qreal h) {
1824 constexpr qreal zero(.0);
1825 return QSizeF(std::max(zero, w), std::max(zero, h)).toSize();
1826 };
1827
1828 if (background) {
1829 metrics.bgImplicitSize = elementSize(background->width(), background->height());
1830 metrics.margins = elementMargins(background);
1831 }
1832 const auto *textProps = props->text();
1833 if (textProps) {
1834 metrics.textPadding = QMargins(qSaturateRound(textProps->leftPadding()),
1835 qSaturateRound(textProps->topPadding()),
1836 qSaturateRound(textProps->rightPadding()),
1837 qSaturateRound(textProps->bottomPadding()));
1838 }
1839 const auto *indicator = props->indicator();
1840 if (indicator) {
1841 metrics.indicatorMargins = elementMargins(indicator);
1842 metrics.indicatorImplicitSize = elementSize(indicator->width(), indicator->height());
1843 }
1844 const auto *handle = props->handle();
1845 if (handle) {
1846 metrics.handleImplicitSize = elementSize(handle->width(), handle->height());
1847 metrics.handleMargins = elementMargins(handle);
1848 }
1849 return metrics;
1850}
1851
1852/*!
1853 Constructs a QStyleKitStyle with no style loaded.
1854
1855 Use \l setStylePath() to load a QML \l Style after construction. Until a
1856 Style loads successfully, the widgets use an empty fallback style.
1857*/
1858QStyleKitStyle::QStyleKitStyle()
1859 : QCommonStyle(*new QStyleKitStylePrivate())
1860{
1861}
1862
1863/*!
1864 Constructs a QStyleKitStyle and loads the QML \l Style at \a filePath.
1865 See the \l stylePath property for the accepted path forms.
1866
1867 If the path is invalid or the root object of the loaded component is not
1868 a \l Style, QStyleKitStyle emits a warning and the widgets use an empty
1869 fallback style until a valid \l stylePath is set.
1870*/
1871QStyleKitStyle::QStyleKitStyle(const QString &filePath)
1872 : QCommonStyle(*new QStyleKitStylePrivate())
1873{
1874 Q_D(QStyleKitStyle);
1875 d->stylePath = filePath;
1876 if (!d->loadStyle()) {
1877 d->stylePath.clear();
1878 qWarning("QStyleKitStyle: Failed to load style from %s", qPrintable(filePath));
1879 }
1880}
1881
1882/*!
1883 Destroys the QStyleKitStyle.
1884*/
1885QStyleKitStyle::~QStyleKitStyle()
1886{
1887}
1888
1889/*!
1890 Returns the path most recently set for the QML \l Style file.
1891
1892 \sa setStylePath()
1893*/
1894QString QStyleKitStyle::stylePath() const
1895{
1896 Q_D(const QStyleKitStyle);
1897 return d->stylePath;
1898}
1899
1900/*!
1901 Loads the QML \l Style at \a filePath and applies it to all widgets.
1902
1903 \a filePath is a path to a local file or a path to a file in the resource
1904 file system; see the \l stylePath property for the accepted forms. If it is
1905 the same as the current \l stylePath, this function does nothing.
1906
1907 If the new style does not load, QStyleKitStyle emits a warning, keeps
1908 the previously loaded style active, and does not emit \l stylePathChanged().
1909
1910 \sa stylePath()
1911*/
1912void QStyleKitStyle::setStylePath(const QString &filePath)
1913{
1914 Q_D(QStyleKitStyle);
1915 if (d->stylePath == filePath)
1916 return;
1917
1918 const QString oldThemeName = themeName();
1919 const QStringList oldThemeNames = availableThemeNames();
1920 const QStringList oldCustomThemeNames = customThemeNames();
1921
1922 const QString previousPath = d->stylePath;
1923 d->stylePath = filePath;
1924 if (!d->loadStyle()) {
1925 d->stylePath = previousPath;
1926 return;
1927 }
1928 d->updateStyle();
1929 if (const QStringList names = availableThemeNames(); names != oldThemeNames)
1930 emit availableThemeNamesChanged(names);
1931 if (const QStringList names = customThemeNames(); names != oldCustomThemeNames)
1932 emit customThemeNamesChanged(names);
1933 emit stylePathChanged(d->stylePath);
1934}
1935
1936/*!
1937 Returns the name of the requested theme, or an empty string when no
1938 \l Style is loaded.
1939
1940 When the theme name is \c System, this function returns \c System rather
1941 than the \c Light or \c Dark theme that the platform color scheme
1942 resolves to.
1943
1944 \sa setThemeName(), availableThemeNames()
1945*/
1946QString QStyleKitStyle::themeName() const
1947{
1948 Q_D(const QStyleKitStyle);
1949 return d->style ? d->style->themeName() : QString();
1950}
1951
1952/*!
1953 Activates the theme named \a themeName.
1954
1955 \a themeName must be one of the entries in \l availableThemeNames(),
1956 which includes the special name \c System for following the platform
1957 color scheme. The comparison ignores case.
1958
1959 If no \l Style is loaded, this function emits a warning and returns
1960 without changing the active theme. If a Style is loaded but \a themeName
1961 matches none of its themes, the Style emits a warning and applies no
1962 theme.
1963
1964 \sa themeName(), availableThemeNames()
1965*/
1966void QStyleKitStyle::setThemeName(const QString &themeName)
1967{
1968 Q_D(QStyleKitStyle);
1969 if (!d->style) {
1970 qWarning("QStyleKitStyle: No style loaded, cannot set theme name.");
1971 return;
1972 }
1973 if (d->style->themeName() == themeName)
1974 return;
1975 d->style->setThemeName(themeName);
1976 d->updateStyle();
1977 emit themeNameChanged(d->style->themeName());
1978}
1979
1980/*!
1981 Returns the names of all themes that the loaded \l Style exposes. The
1982 list always includes \c System, and includes \c Light and \c Dark when
1983 the Style defines those themes, together with any custom themes that
1984 the style author defines. Returns an empty list when no style is
1985 loaded.
1986
1987 \sa customThemeNames(), themeName()
1988*/
1989QStringList QStyleKitStyle::availableThemeNames() const
1990{
1991 Q_D(const QStyleKitStyle);
1992 return d->style ? d->style->availableThemeNames() : QStringList();
1993}
1994
1995/*!
1996 Returns the names of the custom themes defined by the loaded
1997 \l Style, excluding the built-in \c Light and \c Dark themes.
1998 Returns an empty list when no style is loaded.
1999
2000 \sa availableThemeNames()
2001*/
2002QStringList QStyleKitStyle::customThemeNames() const
2003{
2004 Q_D(const QStyleKitStyle);
2005 return d->style ? d->style->customThemeNames() : QStringList();
2006}
2007
2008/*! \reimp */
2009void QStyleKitStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
2010 const QWidget *w) const
2011{
2012 Q_D(const QStyleKitStyle);
2013
2014 switch (pe) {
2015#if QT_CONFIG(tooltip)
2016 case PE_PanelTipLabel: {
2017 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ToolTip, opt->state);
2018 if (!r.isValid())
2019 break;
2020 r.drawBackground(opt->rect.marginsRemoved(r.metrics->margins), p);
2021 return;
2022 }
2023#endif
2024#if QT_CONFIG(menu)
2025 case PE_PanelMenu: {
2026 const auto controlType = w && w->inherits("QComboBoxPrivateContainer")
2027 ? QQStyleKitReader::ControlType::Popup
2028 : QQStyleKitReader::ControlType::Menu;
2029 const auto r = d->resolve(w, controlType, opt->state);
2030 if (!r.isValid())
2031 break;
2032 r.drawBackground(opt->rect.marginsRemoved(r.metrics->margins), p);
2033 return;
2034 }
2035 case PE_FrameMenu:
2036 // already drawn in PE_PanelMenu
2037 return;
2038#endif // QT_CONFIG(menu)
2039#if QT_CONFIG(menubar)
2040 case PE_PanelMenuBar: {
2041 const auto r = d->resolve(w, QQStyleKitReader::ControlType::MenuBar, opt->state);
2042 if (!r.isValid())
2043 break;
2044 r.drawBackground(opt->rect.marginsRemoved(r.metrics->margins), p);
2045 return;
2046 }
2047#endif // QT_CONFIG(menubar)
2048 case PE_FrameButtonBevel:
2049 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2050 const auto controlType = btn->features & QStyleOptionButton::Flat
2051 ? QQStyleKitReader::ControlType::FlatButton
2052 : QQStyleKitReader::ControlType::Button;
2053 const auto r = d->resolve(w, controlType, btn->state);
2054 if (!r.isValid())
2055 break;
2056 r.drawBackground(opt->rect, p);
2057 return;
2058 }
2059 break;
2060 case PE_Frame: {
2061 QQStyleKitReader::ControlType controlType;
2062 const bool isPopup = w
2063 && (false
2064#if QT_CONFIG(combobox)
2065 || w->inherits("QComboBoxPrivateContainer")
2066#endif
2067 );
2068 if (isPopup)
2069 controlType = QQStyleKitReader::ControlType::Popup;
2070#if QT_CONFIG(lineedit)
2071 else if (qobject_cast<const QLineEdit *>(w))
2072 controlType = QQStyleKitReader::ControlType::TextField;
2073#endif
2074 else
2075 controlType = QQStyleKitReader::ControlType::Frame;
2076 const auto r = d->resolve(w, controlType, opt->state);
2077 if (!r.isValid())
2078 break;
2079 r.drawBackground(opt->rect, p);
2080 return;
2081 }
2082#if QT_CONFIG(lineedit)
2083 case PE_PanelLineEdit:
2084 if (const auto *lineEdit = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
2085 // LineEdit sets Sunken flag to indicate Sunken frame,
2086 // but the style uses it to indicate pressed state, so ignore it
2087 QStyleOption lineEditOpt(*lineEdit);
2088 lineEditOpt.state &= ~QStyle::State_Sunken;
2089 const auto r = d->resolve(w, QQStyleKitReader::ControlType::TextField,
2090 lineEditOpt.state);
2091 if (!r.isValid())
2092 break;
2093
2094 // LineEdit draws its own text using the Text role so update that role in the palette
2095 if (auto *le = qobject_cast<const QLineEdit *>(w)) {
2096 if (const auto *txt = r.text(); txt && txt->isDefined(QQSK::Property::Color)) {
2097 QPalette stylePalette;
2098 stylePalette.setColor(QPalette::Text, txt->color());
2099 d->setStylePalette(const_cast<QLineEdit *>(le), stylePalette);
2100 }
2101 const_cast<QStyleKitStylePrivate *>(d)->setStyleFont(const_cast<QLineEdit *>(le),
2102 r.font());
2103 }
2104
2105 const QObject *parent = w ? w->parent() : nullptr;
2106# if QT_CONFIG(spinbox)
2107 const bool isInSpinBox = qobject_cast<const QAbstractSpinBox *>(parent);
2108# else
2109 const bool isInSpinBox = false;
2110# endif
2111# if QT_CONFIG(combobox)
2112 const bool isInComboBox = qobject_cast<const QComboBox *>(parent);
2113# else
2114 const bool isInComboBox = false;
2115# endif
2116 // For spinbox and combobox, the line edit doesn't have its own background in the Controls style
2117 if (isInSpinBox || isInComboBox)
2118 return;
2119
2120 r.drawBackground(opt->rect, p);
2121 return;
2122 }
2123 break;
2124#endif // QT_CONFIG(lineedit)
2125#if QT_CONFIG(itemviews)
2126 case PE_PanelItemViewItem: {
2127 const auto r = d->resolveSubElement(w, opt, itemViewControlType(opt), opt->state);
2128 if (!r.isValid())
2129 break;
2130 r.drawBackground(opt->rect, p);
2131 return;
2132 }
2133#endif // QT_CONFIG(itemviews)
2134 case PE_IndicatorCheckBox:
2135 case PE_IndicatorRadioButton: {
2136 const auto controlType = pe == PE_IndicatorCheckBox
2137 ? QQStyleKitReader::ControlType::CheckBox
2138 : QQStyleKitReader::ControlType::RadioButton;
2139 const auto r = d->resolve(w, controlType, opt->state);
2140 if (!r.isValid())
2141 break;
2142 r.drawIndicator(opt->rect, p);
2143 return;
2144 }
2145 case PE_IndicatorArrowDown: {
2146 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ComboBox, opt->state);
2147 if (!r.isValid())
2148 break;
2149 r.drawIndicator(opt->rect, p);
2150 return;
2151 }
2152 case PE_IndicatorItemViewItemCheck: {
2153 // track = false: Checked state is synthetic
2154 const auto r = d->resolveSubElement(w, opt, itemViewControlType(opt), opt->state, false);
2155 if (!r.isValid())
2156 break;
2157 r.drawIndicator(opt->rect, p);
2158 return;
2159 }
2160#if QT_CONFIG(spinbox)
2161 case PE_IndicatorSpinUp:
2162 case PE_IndicatorSpinDown: {
2163 const auto r = d->resolve(w, QQStyleKitReader::ControlType::SpinBox, opt->state);
2164 if (!r.isValid())
2165 break;
2166 r.drawSubIndicator(pe == PE_IndicatorSpinUp, opt->rect, p);
2167 return;
2168 }
2169#endif // QT_CONFIG(spinbox)
2170#if QT_CONFIG(groupbox)
2171 case PE_FrameGroupBox: {
2172 const auto r = d->resolve(w, QQStyleKitReader::ControlType::GroupBox, opt->state);
2173 if (!r.isValid())
2174 break;
2175 r.drawBackground(opt->rect, p);
2176 return;
2177 }
2178#endif // QT_CONFIG(groupbox)
2179#if QT_CONFIG(tabwidget)
2180 case PE_FrameTabWidget: {
2181 const auto r = d->resolve(w, QQStyleKitReader::ControlType::Page, opt->state);
2182 if (!r.isValid())
2183 break;
2184 r.drawBackground(opt->rect, p);
2185 return;
2186 }
2187#endif // QT_CONFIG(tabwidget)
2188#if QT_CONFIG(tabbar)
2189 // Not (yet) supported in StyleKit
2190 case PE_IndicatorTabClose:
2191 case PE_IndicatorTabTearRight:
2192 case PE_IndicatorTabTearLeft:
2193 return;
2194#endif // QT_CONFIG(tabbar)
2195#if QT_CONFIG(toolbutton)
2196 case PE_FrameButtonTool:
2197 case PE_PanelButtonTool: {
2198 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ToolButton, opt->state);
2199 if (!r.isValid())
2200 break;
2201 r.drawBackground(opt->rect, p);
2202 return;
2203 }
2204#endif // QT_CONFIG(toolbutton)
2205#if QT_CONFIG(toolbar)
2206 case PE_IndicatorToolBarHandle:
2207 return; // no handle in Controls style
2208 case PE_IndicatorToolBarSeparator: {
2209 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ToolSeparator, opt->state);
2210 if (!r.isValid())
2211 break;
2212 const auto &metrics = *r.metrics;
2213 // background
2214 QRect frameRect = opt->rect.marginsRemoved(metrics.margins);
2215 r.drawBackground(frameRect, p);
2216 // indicator
2217 const auto *indicator = r.indicator();
2218 QRect contentRect = frameRect.marginsRemoved(metrics.padding);
2219 const QRect indicatorRect = delegateRect(indicator, contentRect, Qt::AlignHCenter,
2220 Qt::AlignVCenter);
2221 r.drawIndicator(visualRect(opt->direction, contentRect, indicatorRect), p);
2222 return;
2223 }
2224#endif
2225 default:
2226 break;
2227 }
2228 QCommonStyle::drawPrimitive(pe, opt, p, w);
2229}
2230
2231/*! \reimp */
2232void QStyleKitStyle::drawControl(ControlElement element, const QStyleOption *opt, QPainter *p,
2233 const QWidget *w) const
2234{
2235 Q_D(const QStyleKitStyle);
2236
2237 switch (element) {
2238 case CE_PushButton:
2239 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2240 proxy()->drawControl(CE_PushButtonBevel, btn, p, w);
2241 QStyleOptionButton btnContent(*btn);
2242 btnContent.rect = subElementRect(SE_PushButtonContents, btn, w);
2243 proxy()->drawControl(CE_PushButtonLabel, &btnContent, p, w);
2244 }
2245 return;
2246 case CE_PushButtonBevel:
2247 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2248 QStyleOptionButton btnBg(*btn);
2249 btnBg.rect = subElementRect(SE_PushButtonBevel, btn, w);
2250 proxy()->drawPrimitive(PE_FrameButtonBevel, &btnBg, p, w);
2251 }
2252 return;
2253 case CE_PushButtonLabel:
2254 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2255 const auto controlType = btn->features & QStyleOptionButton::Flat
2256 ? QQStyleKitReader::ControlType::FlatButton
2257 : QQStyleKitReader::ControlType::Button;
2258 const auto r = d->resolve(w, controlType, btn->state);
2259 if (!r.isValid())
2260 break;
2261
2262 QRect textRect = opt->rect;
2263 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2264 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2265
2266 if (btn->features & QStyleOptionButton::HasMenu) {
2267 int indicatorSize = pixelMetric(PM_MenuButtonIndicator, btn, w);
2268 if (btn->direction == Qt::LeftToRight)
2269 textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
2270 else
2271 textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
2272 }
2273
2274 r.drawLabel(textRect, btn->text, btn->icon, btn->iconSize, btn->state, textFlags,
2275 btn->direction, p);
2276 return;
2277 }
2278 break;
2279 case CE_CheckBox:
2280 case CE_RadioButton:
2281 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2282 const auto controlType = element == CE_CheckBox
2283 ? QQStyleKitReader::ControlType::CheckBox
2284 : QQStyleKitReader::ControlType::RadioButton;
2285 const auto r = d->resolve(w, controlType, btn->state);
2286 if (!r.isValid())
2287 break;
2288 QRect backgroundRect = btn->rect.marginsRemoved(r.metrics->margins);
2289 // background
2290 r.drawBackground(backgroundRect, p);
2291 // label
2292 QStyleOptionButton btnContent(*btn);
2293 const auto contentElement = element == CE_CheckBox
2294 ? SE_CheckBoxContents
2295 : SE_RadioButtonContents;
2296 btnContent.rect = subElementRect(contentElement, btn, w);
2297 const auto labelElement = element == CE_CheckBox
2298 ? CE_CheckBoxLabel
2299 : CE_RadioButtonLabel;
2300 proxy()->drawControl(labelElement, &btnContent, p, w);
2301 // indicator
2302 QStyleOptionButton indicator(*btn);
2303 const auto indicatorElement = element == CE_CheckBox
2304 ? SE_CheckBoxIndicator
2305 : SE_RadioButtonIndicator;
2306 indicator.rect = subElementRect(indicatorElement, btn, w);
2307 const auto primitiveElement = element == CE_CheckBox
2308 ? PE_IndicatorCheckBox
2309 : PE_IndicatorRadioButton;
2310 proxy()->drawPrimitive(primitiveElement, &indicator, p, w);
2311 return;
2312 }
2313 break;
2314 case CE_CheckBoxLabel:
2315 case CE_RadioButtonLabel:
2316 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2317 const auto controlType = element == CE_CheckBoxLabel
2318 ? QQStyleKitReader::ControlType::CheckBox
2319 : QQStyleKitReader::ControlType::RadioButton;
2320 const auto r = d->resolve(w, controlType, btn->state);
2321 if (!r.isValid())
2322 break;
2323 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2324 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2325 r.drawLabel(opt->rect, btn->text, btn->icon, btn->iconSize, btn->state, textFlags,
2326 btn->direction, p);
2327 return;
2328 }
2329 break;
2330#if QT_CONFIG(combobox)
2331 case CE_ComboBoxLabel:
2332 if (const auto *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
2333 if (comboBox->editable && comboBox->currentIcon.isNull())
2334 return;
2335 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ComboBox, comboBox->state);
2336 if (!r.isValid())
2337 break;
2338 const QRect editRect = subControlRect(CC_ComboBox, comboBox, SC_ComboBoxEditField, w);
2339 const QRect textRect = editRect.marginsRemoved(r.metrics->textPadding);
2340 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2341 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2342 if (comboBox->editable) {
2343 const QPixmap pm = iconPixmap(comboBox->currentIcon, comboBox->iconSize,
2344 comboBox->state, p);
2345 // QComboBox leaves iconSize + 4 free for the icon, in front of the line edit
2346 const QRect iconSlot = alignedRect(
2347 comboBox->direction, Qt::AlignLeft | Qt::AlignVCenter,
2348 QSize(comboBox->iconSize.width() + 4, editRect.height()), editRect);
2349 p->drawPixmap(alignedRect(comboBox->direction, Qt::AlignCenter,
2350 pm.deviceIndependentSize().toSize(), iconSlot),
2351 pm);
2352 return;
2353 }
2354 r.drawLabel(textRect, comboBox->currentText, comboBox->currentIcon, comboBox->iconSize,
2355 comboBox->state, textFlags, comboBox->direction, p);
2356 return;
2357 }
2358 break;
2359#endif // QT_CONFIG(combobox)
2360#if QT_CONFIG(progressbar)
2361 case CE_ProgressBar:
2362 if (const QStyleOptionProgressBar *progressBar =
2363 qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
2364 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ProgressBar,
2365 progressBar->state);
2366 if (!r.isValid())
2367 break;
2368 QRect backgroundRect = progressBar->rect.marginsRemoved(r.metrics->margins);
2369 // background
2370 r.drawBackground(backgroundRect, p);
2371 // groove
2372 QStyleOptionProgressBar contents(*progressBar);
2373 contents.rect = subElementRect(SE_ProgressBarGroove, progressBar, w);
2374 const QRect grooveRect = contents.rect;
2375 proxy()->drawControl(CE_ProgressBarGroove, &contents, p, w);
2376 // track
2377 contents.rect = subElementRect(SE_ProgressBarContents, progressBar, w);
2378 // The track is the groove's foreground child, so it inherits the indicator's
2379 // transform
2380 QPainterStateGuard stateGuard(p);
2381 if (applyDelegateTransform(p, r.indicator(), grooveRect))
2382 proxy()->drawControl(CE_ProgressBarContents, &contents, p, w);
2383 // We intentionally don't draw the label as it is not drawn on the Controls Style
2384 return;
2385 }
2386 break;
2387 case CE_ProgressBarGroove: {
2388 // groove = indicator background
2389 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ProgressBar, opt->state);
2390 if (!r.isValid())
2391 break;
2392 drawStyledItemRect(r.indicator(), opt->rect, p);
2393 return;
2394 }
2395 case CE_ProgressBarContents:
2396 // contents = indicator foreground
2397 if (const auto *progressBar = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
2398 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ProgressBar,
2399 progressBar->state);
2400 if (!r.isValid())
2401 break;
2402 const auto progress = progressBar->progress;
2403 const auto ratio = progressBar->maximum > progressBar->minimum
2404 ? (progress - progressBar->minimum)
2405 / static_cast<qreal>(progressBar->maximum - progressBar->minimum)
2406 : 0;
2407 const auto width = static_cast<int>(progressBar->rect.width() * ratio);
2408 const bool reverse = (progressBar->direction == Qt::RightToLeft)
2409 != progressBar->invertedAppearance;
2410 const auto x = reverse
2411 ? progressBar->rect.x() + progressBar->rect.width() - width
2412 : progressBar->rect.left();
2413 const auto contentsRect = QRect(x, progressBar->rect.y(),
2414 width, progressBar->rect.height());
2415 const auto *foreground = r.indicator() ? r.indicator()->foreground() : nullptr;
2416 if (foreground && foreground->visible() && foreground->opacity() > 0) {
2417 QPainterStateGuard stateGuard(p);
2418 if (applyDelegateTransform(p, foreground, progressBar->rect))
2419 drawStyledItemContents(foreground, contentsRect, p);
2420 }
2421 return;
2422 }
2423 break;
2424#endif // QT_CONFIG(progressbar)
2425#if QT_CONFIG(itemviews)
2426 case CE_ItemViewItem:
2427 if (const auto *itemViewOption = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
2428 const auto r = d->resolveSubElement(w, opt, itemViewControlType(opt), opt->state);
2429 if (!r.isValid())
2430 break;
2431 QStyleOptionViewItem optBg(*itemViewOption);
2432 optBg.rect = optBg.rect.marginsRemoved(r.metrics->margins);
2433 QRect indicatorRect = subElementRect(SE_ItemViewItemCheckIndicator, itemViewOption, w);
2434 QRect iconRect = subElementRect(SE_ItemViewItemDecoration, itemViewOption, w);
2435 QRect textRect = subElementRect(SE_ItemViewItemText, itemViewOption, w);
2436 // Capture text properties + font now, before the indicator
2437 // drawPrimitive below potentially mutates the reader's state
2438 const auto *itemTextProps = r.text();
2439 const QFont itemFont = r.font();
2440
2441 // background
2442 proxy()->drawPrimitive(PE_PanelItemViewItem, &optBg, p, w);
2443
2444 // indicator
2445 if (itemViewOption->features & QStyleOptionViewItem::HasCheckIndicator) {
2446 QStyleOptionViewItem option(*itemViewOption);
2447 option.rect = indicatorRect;
2448 option.state = option.state & ~QStyle::State_HasFocus;
2449
2450 switch (itemViewOption->checkState) {
2451 case Qt::Unchecked:
2452 option.state |= QStyle::State_Off;
2453 break;
2454 case Qt::PartiallyChecked:
2455 option.state |= QStyle::State_NoChange;
2456 break;
2457 case Qt::Checked:
2458 option.state |= QStyle::State_On;
2459 break;
2460 }
2461 proxy()->drawPrimitive(QStyle::PE_IndicatorItemViewItemCheck, &option, p, w);
2462 }
2463
2464 // icon
2465 QIcon::Mode mode = QIcon::Normal;
2466 if (!(itemViewOption->state & QStyle::State_Enabled))
2467 mode = QIcon::Disabled;
2468 else if (itemViewOption->state & QStyle::State_Selected)
2469 mode = QIcon::Selected;
2470 QIcon::State state = itemViewOption->state & QStyle::State_Open
2471 ? QIcon::On
2472 : QIcon::Off;
2473 itemViewOption->icon.paint(p, iconRect, itemViewOption->decorationAlignment, mode,
2474 state);
2475
2476 // draw text
2477 uint textFlags = Qt::TextShowMnemonic;
2478 if (!styleHint(SH_UnderlineShortcut, opt, w))
2479 textFlags |= Qt::TextHideMnemonic;
2480 drawControlText(itemTextProps, itemFont, textRect, itemViewOption->text, textFlags,
2481 p, Qt::AlignLeft | Qt::AlignVCenter);
2482 return;
2483 }
2484 break;
2485#endif // QT_CONFIG(itemviews)
2486#ifndef QT_NO_FRAME
2487 case CE_ShapedFrame: {
2488# if QT_CONFIG(scrollarea)
2489 if (qobject_cast<const QAbstractScrollArea *>(w))
2490 // ScrollView has no styling in Controls, keep consistent
2491 return;
2492# endif
2493 auto controlType = QQStyleKitReader::ControlType::Frame;
2494# if QT_CONFIG(combobox)
2495 if (w && w->inherits("QComboBoxPrivateContainer"))
2496 controlType = QQStyleKitReader::ControlType::Popup;
2497# endif
2498# if QT_CONFIG(textedit)
2499 else if (w && qobject_cast<const QTextEdit *>(w))
2500 controlType = QQStyleKitReader::ControlType::TextArea;
2501# endif
2502# if QT_CONFIG(label)
2503 else if (w && qobject_cast<const QLabel *>(w))
2504 controlType = QQStyleKitReader::ControlType::Label;
2505# endif
2506 // Fallback to Frame
2507 if (qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
2508 const auto r = d->resolve(w, controlType, opt->state);
2509 if (!r.isValid())
2510 break;
2511 QRect backgroundRect = opt->rect.marginsRemoved(r.metrics->margins);
2512 r.drawBackground(backgroundRect, p);
2513 return;
2514 }
2515 break;
2516 }
2517#endif // QT_NO_FRAME
2518#if QT_CONFIG(scrollbar)
2519 case CE_ScrollBarSlider: {
2520 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ScrollBar, opt->state);
2521 if (!r.isValid())
2522 break;
2523 r.drawIndicator(opt->rect, p);
2524 return;
2525 }
2526#endif // QT_CONFIG(scrollbar)
2527#if QT_CONFIG(toolbutton)
2528 case CE_ToolButtonLabel:
2529 if (const auto *tool = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
2530 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ToolButton, tool->state);
2531 if (!r.isValid())
2532 break;
2533 const auto *metrics = r.metrics;
2534 QRect rect = tool->rect.marginsRemoved(metrics->textPadding);
2535
2536 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2537 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2538
2539 const bool hasArrow = tool->features & QStyleOptionToolButton::Arrow;
2540 if ((!hasArrow && tool->icon.isNull() && !tool->text.isEmpty())
2541 || tool->toolButtonStyle == Qt::ToolButtonTextOnly) {
2542 r.drawText(rect, tool->text, textFlags, p);
2543 return;
2544 }
2545
2546 const bool textUnderIcon = tool->toolButtonStyle == Qt::ToolButtonTextUnderIcon;
2547 if (hasArrow || tool->icon.isNull()) {
2548 if (tool->toolButtonStyle != Qt::ToolButtonIconOnly && !tool->text.isEmpty()) {
2549 r.drawText(rect, tool->text, textFlags, p,
2550 textUnderIcon ? Qt::AlignCenter : Qt::AlignLeft | Qt::AlignVCenter);
2551 }
2552 return;
2553 }
2554
2555 const QString text = tool->toolButtonStyle == Qt::ToolButtonIconOnly
2556 ? QString()
2557 : tool->text;
2558 r.drawLabel(rect, text, tool->icon, tool->iconSize, tool->state, textFlags,
2559 tool->direction, p, Qt::AlignHCenter | Qt::AlignVCenter, textUnderIcon);
2560 return;
2561 }
2562 break;
2563#endif // QT_CONFIG(toolbutton)
2564#if QT_CONFIG(menu)
2565 case CE_MenuItem:
2566 if (const auto *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
2567 using QtPrivate::qSaturateRound;
2568 // MenuItemSeperator
2569 if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
2570 const auto r = d->resolve(w, QQStyleKitReader::ControlType::MenuSeparator,
2571 menuItem->state);
2572 if (!r.isValid())
2573 break;
2574 const auto metrics = r.metrics;
2575 QRect contentRect = opt->rect
2576 .marginsRemoved(metrics->margins)
2577 .marginsRemoved(metrics->padding);
2578 const auto *indicator = r.indicator();
2579 const QRect indicatorRect = delegateRect(
2580 indicator, contentRect, Qt::AlignHCenter, Qt::AlignVCenter);
2581 r.drawIndicator(visualRect(opt->direction, contentRect, indicatorRect), p);
2582 return;
2583 }
2584 // MenuItem
2585 QStyle::State adjustedState = menuItem->state;
2586 if (adjustedState & State_Selected)
2587 adjustedState |= State_MouseOver;
2588
2589 const auto r = d->resolveSubElement(w, opt, QQStyleKitReader::ControlType::MenuItem,
2590 adjustedState);
2591 if (!r.isValid())
2592 break;
2593
2594 // background
2595 r.drawBackground(opt->rect.marginsRemoved(r.metrics->margins), p);
2596
2597 // indicators
2598 const QRect contentRect = opt->rect.marginsRemoved(r.metrics->padding);
2599 const auto *indicator = r.indicator();
2600 const auto *first = indicator ? indicator->first() : nullptr;
2601 const auto *second = indicator ? indicator->second() : nullptr;
2602 int leftOffset = 0, rightOffset = 0;
2603 const int spacing = r.metrics->spacing;
2604 QRect firstDrawRect, secondDrawRect;
2605 auto placeSubIndicator = [&](const QQStyleKitIndicatorProperties *sub,
2606 QRect &drawRect) {
2607 if (!sub)
2608 return;
2609 const int slotW = qSaturateRound(sub->leftMargin() + sub->width() + sub->rightMargin());
2610 if (sub->alignment() & Qt::AlignRight) {
2611 const QRect slot(contentRect.right() - rightOffset - slotW, contentRect.top(),
2612 slotW, contentRect.height());
2613 drawRect = delegateRect(sub, slot, Qt::AlignRight, Qt::AlignVCenter);
2614 rightOffset += slotW + spacing;
2615 } else {
2616 const QRect slot(contentRect.left() + leftOffset, contentRect.top(), slotW,
2617 contentRect.height());
2618 drawRect = delegateRect(sub, slot, Qt::AlignLeft, Qt::AlignVCenter);
2619 leftOffset += slotW + spacing;
2620 }
2621 };
2622 if (menuItem->menuHasCheckableItems)
2623 placeSubIndicator(first, firstDrawRect);
2624 if (menuItem->menuItemType == QStyleOptionMenuItem::SubMenu)
2625 placeSubIndicator(second, secondDrawRect);
2626
2627 if (first && menuItem->checkType != QStyleOptionMenuItem::NotCheckable
2628 && menuItem->checked) {
2629 r.drawSubIndicator(
2630 true, visualRect(menuItem->direction, contentRect, firstDrawRect), p);
2631 }
2632
2633 if (second && menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {
2634 r.drawSubIndicator(
2635 false, visualRect(menuItem->direction, contentRect, secondDrawRect), p);
2636 }
2637
2638 // text
2639 QRect textRect = contentRect
2640 .adjusted(leftOffset, 0, -rightOffset, 0)
2641 .marginsRemoved(r.metrics->textPadding);
2642 // Reserve the icon column in all items if any item in the menu has an icon
2643 if (menuItem->maxIconWidth > 0) {
2644 const int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, w);
2645 if (!menuItem->icon.isNull()) {
2646 const QPixmap pm = iconPixmap(menuItem->icon, QSize(iconExtent, iconExtent),
2647 menuItem->state, p);
2648 const QSize pmSize = pm.size() / pm.devicePixelRatio();
2649 const QRect iconColumn(textRect.left(), textRect.top(), iconExtent,
2650 textRect.height());
2651 p->drawPixmap(visualRect(menuItem->direction, contentRect,
2652 alignedRect(Qt::LeftToRight, Qt::AlignCenter, pmSize,
2653 iconColumn)),
2654 pm);
2655 }
2656 textRect.setLeft(textRect.left() + iconExtent + r.metrics->spacing);
2657 }
2658
2659 const int tabIdx = menuItem->text.indexOf(QLatin1Char('\t'));
2660 const QString label = tabIdx >= 0 ? menuItem->text.left(tabIdx) : menuItem->text;
2661 const QString shortcut = tabIdx >= 0 ? menuItem->text.mid(tabIdx + 1) : QString();
2662 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2663 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2664 QRect labelRect = textRect;
2665 if (!shortcut.isEmpty() && menuItem->reservedShortcutWidth > 0) {
2666 const QRect shortcutRect(textRect.right() - menuItem->reservedShortcutWidth + 1,
2667 textRect.top(), menuItem->reservedShortcutWidth,
2668 textRect.height());
2669 labelRect.setRight(shortcutRect.left() - r.metrics->spacing - 1);
2670 const int shortcutFlags =
2671 int(QStyle::visualAlignment(menuItem->direction,
2672 Qt::AlignRight | Qt::AlignVCenter))
2673 | int(textFlags);
2674 p->save();
2675 p->setFont(r.font().resolve(p->font()));
2676 p->setBrush(Qt::NoBrush);
2677 if (const auto *shortcutText = r.text())
2678 p->setPen(shortcutText->color());
2679 p->drawText(visualRect(menuItem->direction, contentRect, shortcutRect),
2680 shortcutFlags, shortcut);
2681 p->restore();
2682 }
2683 r.drawText(visualRect(menuItem->direction, contentRect, labelRect), label, textFlags, p,
2684 Qt::AlignLeft | Qt::AlignVCenter);
2685 return;
2686 }
2687 break;
2688 // no tearoff or bottom scroller support in Controls style,
2689 // so make it consistent and don't draw them
2690 case CE_MenuScroller:
2691 case CE_MenuTearoff:
2692 return;
2693 case CE_MenuEmptyArea:
2694 return;
2695#endif // QT_CONFIG(menu)
2696#if QT_CONFIG(menubar)
2697 case CE_MenuBarEmptyArea:
2698 return;
2699 case CE_MenuBarItem:
2700 if (const auto *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
2701 QStyle::State adjustedState = menuItem->state;
2702 if (adjustedState & State_Selected)
2703 adjustedState |= State_MouseOver;
2704 const auto r = d->resolveSubElement(w, opt, QQStyleKitReader::ControlType::MenuBarItem,
2705 adjustedState);
2706 if (!r.isValid())
2707 break;
2708 r.drawBackground(opt->rect.marginsRemoved(r.metrics->margins), p);
2709 const QRect textRect = opt->rect.marginsRemoved(
2710 r.metrics->margins + r.metrics->padding + r.metrics->textPadding);
2711 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2712 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2713 const int iconExtent = proxy()->pixelMetric(PM_SmallIconSize, opt, w);
2714 // QMenuBar sizes items with an icon to show only the icon
2715 r.drawLabel(textRect, menuItem->icon.isNull() ? menuItem->text : QString(),
2716 menuItem->icon, QSize(iconExtent, iconExtent), adjustedState, textFlags,
2717 menuItem->direction, p);
2718 return;
2719 }
2720 break;
2721#endif // QT_CONFIG(menubar)
2722#if QT_CONFIG(tabbar)
2723 case CE_TabBarTab:
2724 if (const auto *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
2725 const auto r = d->resolveSubElement(w, opt, QQStyleKitReader::ControlType::TabButton,
2726 tab->state);
2727 if (!r.isValid())
2728 break;
2729 const auto &m = *r.metrics;
2730
2731 const QRect backgroundRect = opt->rect.marginsRemoved(m.margins);
2732 r.drawBackground(backgroundRect, p);
2733
2734 const QRect contentRect = backgroundRect.marginsRemoved(m.padding + m.textPadding);
2735 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
2736 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
2737
2738 r.drawLabel(contentRect, tab->text, tab->icon, tab->iconSize, tab->state, textFlags,
2739 tab->direction, p, Qt::AlignCenter);
2740 return;
2741 }
2742 break;
2743#endif // QT_CONFIG(tabbar)
2744#if QT_CONFIG(toolbar)
2745 case CE_ToolBar:
2746 if (const auto *toolBar = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
2747 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ToolBar, toolBar->state);
2748 if (!r.isValid())
2749 break;
2750 r.drawBackground(opt->rect.marginsRemoved(r.metrics->margins), p);
2751 return;
2752 }
2753 break;
2754#endif // QT_CONFIG(toolbar)
2755 default:
2756 break;
2757 }
2758 QCommonStyle::drawControl(element, opt, p, w);
2759}
2760
2761/*! \reimp */
2762QRect QStyleKitStyle::subElementRect(SubElement r, const QStyleOption *opt,
2763 const QWidget *widget) const
2764{
2765 using QtPrivate::qSaturateRound;
2766 Q_D(const QStyleKitStyle);
2767
2768 switch (r) {
2769 case SE_PushButtonBevel:
2770 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2771 const auto controlType = btn->features & QStyleOptionButton::Flat
2772 ? QQStyleKitReader::ControlType::FlatButton
2773 : QQStyleKitReader::ControlType::Button;
2774 const auto resolved = d->resolveLayout(controlType, opt->state);
2775 if (!resolved.isValid())
2776 break;
2777 const auto &metrics = *resolved.metrics;
2778 QRect rect = opt->rect.marginsRemoved(metrics.margins);
2779 return visualRect(opt->direction, opt->rect, rect);
2780 }
2781 break;
2782 case SE_PushButtonContents:
2783 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2784 const auto controlType = btn->features & QStyleOptionButton::Flat
2785 ? QQStyleKitReader::ControlType::FlatButton
2786 : QQStyleKitReader::ControlType::Button;
2787 const auto resolved = d->resolveLayout(controlType, opt->state);
2788 if (!resolved.isValid())
2789 break;
2790 const auto &metrics = *resolved.metrics;
2791 QRect rect = opt->rect.marginsRemoved(
2792 metrics.margins + metrics.padding + metrics.textPadding);
2793 return visualRect(opt->direction, opt->rect, rect);
2794 }
2795 break;
2796 case SE_CheckBoxContents:
2797 case SE_RadioButtonContents: {
2798 const auto controlType = r == SE_CheckBoxContents
2799 ? QQStyleKitReader::ControlType::CheckBox
2800 : QQStyleKitReader::ControlType::RadioButton;
2801 const auto resolved = d->resolveLayout(controlType, opt->state);
2802 if (!resolved.isValid())
2803 break;
2804 const auto &metrics = *resolved.metrics;
2805 QRect contentsRect = opt->rect.marginsRemoved(metrics.margins + metrics.padding);
2806 const auto subElement = r == SE_CheckBoxContents
2807 ? SE_CheckBoxIndicator
2808 : SE_RadioButtonIndicator;
2809 QRect indicatorRect = visualRect(opt->direction, opt->rect,
2810 subElementRect(subElement, opt, widget));
2811 const int spacing = metrics.spacing;
2812 const auto *indicator = resolved.indicator();
2813 const uint alignment = indicator
2814 ? resolvedAlignment(indicator->alignment(), Qt::AlignLeft, Qt::AlignVCenter)
2815 : uint(Qt::AlignLeft | Qt::AlignVCenter);
2816 if (alignment & Qt::AlignLeft) {
2817 contentsRect.setLeft(indicatorRect.right() + spacing + metrics.textPadding.left());
2818 } else if (alignment & Qt::AlignHCenter) {
2819 contentsRect.setLeft(indicatorRect.right() + spacing + metrics.textPadding.left());
2820 contentsRect.setRight(indicatorRect.left() - spacing - metrics.textPadding.right());
2821 } else {
2822 contentsRect.setRight(indicatorRect.left() - spacing - metrics.textPadding.right());
2823 }
2824 return visualRect(opt->direction, opt->rect, contentsRect);
2825 }
2826 case SE_CheckBoxIndicator:
2827 case SE_RadioButtonIndicator: {
2828 const auto controlType = r == SE_CheckBoxIndicator
2829 ? QQStyleKitReader::ControlType::CheckBox
2830 : QQStyleKitReader::ControlType::RadioButton;
2831 const auto resolved = d->resolveLayout(controlType, opt->state);
2832 if (!resolved.isValid())
2833 break;
2834 const auto &metrics = *resolved.metrics;
2835 QRect rect = opt->rect.marginsRemoved(metrics.margins);
2836 const auto *indicator = resolved.indicator();
2837 if (!indicator || !indicator->visible())
2838 return rect;
2839
2840 return visualRect(opt->direction, rect,
2841 delegateRect(indicator, rect, Qt::AlignLeft, Qt::AlignVCenter,
2842 metrics.padding));
2843 }
2844#if QT_CONFIG(itemviews)
2845 case SE_ItemViewItemCheckIndicator: {
2846 const auto resolved = d->resolveLayout(itemViewControlType(opt), opt->state);
2847 if (!resolved.isValid())
2848 break;
2849 const auto &metrics = *resolved.metrics;
2850 QRect rect = opt->rect.marginsRemoved(metrics.margins);
2851 const auto *indicator = resolved.indicator();
2852 if (!indicator || !indicator->visible())
2853 return rect;
2854
2855 return visualRect(opt->direction, opt->rect,
2856 delegateRect(indicator, rect, Qt::AlignLeft, Qt::AlignVCenter,
2857 metrics.padding));
2858 }
2859 case SE_ItemViewItemDecoration:
2860 if (const auto *itemViewOption = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
2861 if (!(itemViewOption->features & QStyleOptionViewItem::HasDecoration))
2862 return QRect();
2863 const auto resolved = d->resolveLayout(itemViewControlType(opt), opt->state);
2864 if (!resolved.isValid())
2865 break;
2866 const auto &metrics = *resolved.metrics;
2867 QRect contentsRect = opt->rect.marginsRemoved(metrics.margins + metrics.padding);
2868 if (itemViewOption->features & QStyleOptionViewItem::HasCheckIndicator) {
2869 // Map back to logical coordinates, the result is mirrored below
2870 const QRect indicatorRect = visualRect(opt->direction, opt->rect,
2871 subElementRect(SE_ItemViewItemCheckIndicator, opt, widget));
2872 const auto *checkIndicator = resolved.indicator();
2873 const uint checkAlign = checkIndicator
2874 ? resolvedAlignment(checkIndicator->alignment(), Qt::AlignLeft,
2875 Qt::AlignVCenter)
2876 : uint(Qt::AlignLeft | Qt::AlignVCenter);
2877 if (checkAlign & Qt::AlignLeft) {
2878 contentsRect.setLeft(indicatorRect.right()
2879 + metrics.indicatorMargins.right() + metrics.spacing);
2880 } else if (checkAlign & Qt::AlignRight) {
2881 contentsRect.setRight(indicatorRect.left()
2882 - metrics.indicatorMargins.left() - metrics.spacing);
2883 }
2884 }
2885
2886 const QSize decorationSize = itemViewOption->decorationSize
2887 .boundedTo(contentsRect.size());
2888 QRect decorationRect;
2889 switch (itemViewOption->decorationPosition) {
2890 case QStyleOptionViewItem::Top:
2891 decorationRect = QRect(contentsRect.left(), contentsRect.top(),
2892 contentsRect.width(), decorationSize.height());
2893 break;
2894 case QStyleOptionViewItem::Bottom:
2895 decorationRect = QRect(contentsRect.left(),
2896 contentsRect.bottom() - decorationSize.height() + 1,
2897 contentsRect.width(), decorationSize.height());
2898 break;
2899 case QStyleOptionViewItem::Right:
2900 decorationRect = QRect(contentsRect.right() - decorationSize.width() + 1,
2901 contentsRect.top(), decorationSize.width(),
2902 contentsRect.height());
2903 break;
2904 case QStyleOptionViewItem::Left:
2905 default:
2906 decorationRect = QRect(contentsRect.left(), contentsRect.top(),
2907 decorationSize.width(), contentsRect.height());
2908 break;
2909 }
2910 const uint decorationAlign = resolvedAlignment(itemViewOption->decorationAlignment,
2911 Qt::AlignLeft, Qt::AlignVCenter);
2912 decorationRect = alignedRect(Qt::LeftToRight, Qt::Alignment(decorationAlign),
2913 decorationSize, decorationRect);
2914 return visualRect(opt->direction, opt->rect, decorationRect);
2915 }
2916 break;
2917 case SE_ItemViewItemText:
2918 if (const auto *itemViewOption = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
2919 const auto resolved = d->resolveLayout(itemViewControlType(opt), opt->state);
2920 if (!resolved.isValid())
2921 break;
2922 const auto &metrics = *resolved.metrics;
2923 QRect contentsRect = opt->rect.marginsRemoved(metrics.margins + metrics.padding);
2924 const int spacing = metrics.spacing;
2925
2926 if (itemViewOption->features & QStyleOptionViewItem::HasCheckIndicator) {
2927 // Map back to logical coordinates, the result is mirrored below
2928 const QRect indicatorRect = visualRect(opt->direction, opt->rect,
2929 subElementRect(SE_ItemViewItemCheckIndicator, opt, widget));
2930 const auto *checkIndicator = resolved.indicator();
2931 const uint checkAlign = checkIndicator
2932 ? resolvedAlignment(checkIndicator->alignment(), Qt::AlignLeft,
2933 Qt::AlignVCenter)
2934 : uint(Qt::AlignLeft | Qt::AlignVCenter);
2935 if (checkAlign & Qt::AlignLeft) {
2936 contentsRect.setLeft(
2937 indicatorRect.right() + metrics.indicatorMargins.right() + spacing);
2938 } else if (checkAlign & Qt::AlignRight) {
2939 contentsRect.setRight(
2940 indicatorRect.left() - metrics.indicatorMargins.left() - spacing);
2941 }
2942 }
2943
2944 QRect textRect = contentsRect;
2945 if (itemViewOption->features & QStyleOptionViewItem::HasDecoration) {
2946 const QRect decorationRect = visualRect(opt->direction, opt->rect,
2947 subElementRect(SE_ItemViewItemDecoration, opt, widget));
2948 switch (itemViewOption->decorationPosition) {
2949 case QStyleOptionViewItem::Top:
2950 textRect.setTop(decorationRect.bottom() + spacing);
2951 break;
2952 case QStyleOptionViewItem::Bottom:
2953 textRect.setBottom(decorationRect.top() - spacing);
2954 break;
2955 case QStyleOptionViewItem::Right:
2956 textRect.setRight(decorationRect.left() - spacing);
2957 break;
2958 case QStyleOptionViewItem::Left:
2959 default:
2960 textRect.setLeft(decorationRect.right() + spacing);
2961 break;
2962 }
2963 }
2964
2965 const auto *textProps = resolved.text();
2966 const uint textAlign = textProps
2967 ? resolvedAlignment(textProps->alignment(), Qt::AlignLeft, Qt::AlignVCenter)
2968 : uint(Qt::AlignLeft | Qt::AlignVCenter);
2969 if (textAlign & Qt::AlignLeft) {
2970 textRect.setLeft(textRect.left() + metrics.textPadding.left());
2971 } else if (textAlign & Qt::AlignHCenter) {
2972 textRect.setLeft(textRect.left() + metrics.textPadding.left() / 2);
2973 textRect.setRight(textRect.right() - metrics.textPadding.right() / 2);
2974 } else {
2975 textRect.setRight(textRect.right() - metrics.textPadding.right());
2976 }
2977 if (textAlign & Qt::AlignTop) {
2978 textRect.setTop(textRect.top() + metrics.textPadding.top());
2979 } else if (textAlign & Qt::AlignVCenter) {
2980 textRect.setTop(textRect.top() + metrics.textPadding.top() / 2);
2981 textRect.setBottom(textRect.bottom() - metrics.textPadding.bottom() / 2);
2982 } else {
2983 textRect.setBottom(textRect.bottom() - metrics.textPadding.bottom());
2984 }
2985 return visualRect(opt->direction, opt->rect, textRect);
2986 }
2987 break;
2988#endif // QT_CONFIG(itemviews)
2989 case SE_PushButtonFocusRect:
2990 case SE_CheckBoxClickRect:
2991 case SE_RadioButtonClickRect:
2992 return opt->rect;
2993#if QT_CONFIG(progressbar)
2994 case SE_ProgressBarGroove: {
2995 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ProgressBar,
2996 opt->state);
2997 if (!resolved.isValid())
2998 break;
2999 const auto &metrics = *resolved.metrics;
3000 QRect rect = opt->rect.marginsRemoved(metrics.margins);
3001 const auto *indicator = resolved.indicator();
3002 if (!indicator || !indicator->visible())
3003 return rect;
3004
3005 return visualRect(opt->direction, opt->rect,
3006 delegateRect(indicator, rect, Qt::AlignLeft, Qt::AlignVCenter,
3007 metrics.padding));
3008 }
3009 case SE_ProgressBarContents: {
3010 if (qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
3011 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ProgressBar,
3012 opt->state);
3013 if (!resolved.isValid())
3014 break;
3015 const auto *foreground = resolved.indicator()
3016 ? resolved.indicator()->foreground()
3017 : nullptr;
3018 if (!foreground || !foreground->visible())
3019 return QRect();
3020
3021 QRect indicatorRect = subElementRect(SE_ProgressBarGroove, opt, widget);
3022 // Map back to logical coordinates, the result is mirrored below
3023 indicatorRect = visualRect(opt->direction, opt->rect, indicatorRect);
3024 const QRect foregroundRect = delegateRect(
3025 foreground, indicatorRect, Qt::AlignLeft, Qt::AlignVCenter);
3026 return visualRect(opt->direction, opt->rect, foregroundRect);
3027 }
3028 break;
3029 }
3030#endif // QT_CONFIG(progressbar)
3031 case SE_LineEditContents:
3032 if (qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
3033#if QT_CONFIG(spinbox)
3034 const bool isInSpinBox = widget && qobject_cast<const QSpinBox *>(widget->parentWidget());
3035#else
3036 const bool isInSpinBox = false;
3037#endif
3038 const auto controlType = isInSpinBox ? QQStyleKitReader::ControlType::SpinBox
3039 : QQStyleKitReader::ControlType::TextField;
3040 const auto resolved = d->resolveLayout(controlType, opt->state);
3041 if (!resolved.isValid())
3042 break;
3043 const auto &metrics = *resolved.metrics;
3044 QRect contentsRect = opt->rect.marginsRemoved(metrics.padding);
3045 const auto *textProps = resolved.text();
3046 const uint textAlign = resolvedAlignment(textProps ? textProps->alignment() : 0u,
3047 Qt::AlignLeft, Qt::AlignVCenter);
3048 if (textAlign & Qt::AlignLeft)
3049 contentsRect.setLeft(contentsRect.left() + metrics.textPadding.left());
3050 else if (textAlign & Qt::AlignHCenter) {
3051 contentsRect.setLeft(contentsRect.left() + metrics.textPadding.left() / 2);
3052 contentsRect.setRight(contentsRect.right() - metrics.textPadding.right() / 2);
3053 } else {
3054 contentsRect.setRight(contentsRect.right() - metrics.textPadding.right());
3055 }
3056 if (textAlign & Qt::AlignTop)
3057 contentsRect.setTop(contentsRect.top() + metrics.textPadding.top());
3058 else if (textAlign & Qt::AlignVCenter) {
3059 contentsRect.setTop(contentsRect.top() + metrics.textPadding.top() / 2);
3060 contentsRect.setBottom(contentsRect.bottom() - metrics.textPadding.bottom() / 2);
3061 } else {
3062 contentsRect.setBottom(contentsRect.bottom() - metrics.textPadding.bottom());
3063 }
3064 return visualRect(opt->direction, opt->rect, contentsRect);
3065 }
3066 break;
3067 case SE_ShapedFrameContents:
3068#if QT_CONFIG(combobox)
3069 if (widget && widget->inherits("QComboBoxPrivateContainer")) {
3070 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Popup,
3071 opt->state);
3072 if (!resolved.isValid())
3073 break;
3074 const auto &metrics = *resolved.metrics;
3075 QRect contentsRect = opt->rect.marginsRemoved(
3076 metrics.margins + metrics.padding + metrics.textPadding);
3077 return visualRect(opt->direction, opt->rect, contentsRect);
3078 }
3079#endif
3080#if QT_CONFIG(textedit)
3081 if (qobject_cast<const QTextEdit *>(widget)) {
3082 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::TextArea,
3083 opt->state);
3084 if (!resolved.isValid())
3085 break;
3086 const auto &metrics = *resolved.metrics;
3087 QRect contentsRect = opt->rect.marginsRemoved(
3088 metrics.margins + metrics.padding + metrics.textPadding);
3089 return visualRect(opt->direction, opt->rect, contentsRect);
3090 }
3091#endif // textedit
3092 break;
3093#if QT_CONFIG(tabbar)
3094 case SE_TabBarTabText:
3095 if (const auto *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
3096 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::TabButton,
3097 opt->state);
3098 if (!resolved.isValid())
3099 break;
3100 const auto &metrics = *resolved.metrics;
3101 QRect rect = tab->rect.marginsRemoved(
3102 metrics.margins + metrics.padding + metrics.textPadding);
3103 if (!tab->icon.isNull())
3104 rect.setLeft(rect.left() + tab->iconSize.width() + metrics.spacing);
3105 return visualRect(tab->direction, tab->rect, rect);
3106 }
3107 break;
3108 case SE_TabBarTearIndicatorRight:
3109 case SE_TabBarTearIndicatorLeft:
3110 case SE_TabBarScrollLeftButton:
3111 case SE_TabBarScrollRightButton:
3112 // Not supported
3113 return QRect();
3114#endif // QT_CONFIG(tabbar)
3115#if QT_CONFIG(tabwidget)
3116 case SE_TabWidgetTabContents:
3117 if (qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
3118 // TabWidget corresponds to Page
3119 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Page, opt->state);
3120 if (!resolved.isValid())
3121 break;
3122 const QRect paneRect = subElementRect(SE_TabWidgetTabPane, opt, widget);
3123 const QRect rect = paneRect.marginsRemoved(resolved.metrics->padding);
3124 return visualRect(opt->direction, opt->rect, rect);
3125 }
3126 break;
3127#endif // QT_CONFIG(tabwidget)
3128#if QT_CONFIG(toolbar)
3129 case SE_ToolBarHandle:
3130 // Not supported
3131 return QRect();
3132#endif // QT_CONFIG(toolbar)
3133 default:
3134 break;
3135 }
3136 return QCommonStyle::subElementRect(r, opt, widget);
3137}
3138
3139/*! \reimp */
3140void QStyleKitStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
3141 QPainter *p, const QWidget *w) const
3142{
3143 Q_D(const QStyleKitStyle);
3144
3145 switch (cc) {
3146#if QT_CONFIG(slider)
3147 case CC_Slider:
3148 if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3149 const auto r = d->resolve(w, QQStyleKitReader::ControlType::Slider, slider->state);
3150 if (!r.isValid())
3151 break;
3152 const auto &metrics = *r.metrics;
3153 QRect backgroundRect = opt->rect.marginsRemoved(metrics.margins);
3154
3155 // background
3156 r.drawBackground(backgroundRect, p);
3157
3158 // groove
3159 if (slider->subControls & SC_SliderGroove) {
3160 // groove
3161 const auto grooveRect = proxy()->subControlRect(CC_Slider, opt, SC_SliderGroove, w);
3162 const auto *indicator = r.indicator();
3163 drawStyledItemRect(indicator, grooveRect, p);
3164
3165 // track
3166 const auto *foreground = indicator ? indicator->foreground() : nullptr;
3167 if (foreground && foreground->visible()) {
3168 const bool isHorizontal = slider->orientation == Qt::Horizontal;
3169 const qreal availableW = grooveRect.width()
3170 - foreground->leftMargin() - foreground->rightMargin();
3171 const qreal availableH = grooveRect.height()
3172 - foreground->topMargin() - foreground->bottomMargin();
3173
3174 const qreal range = slider->maximum - slider->minimum;
3175 const qreal ratio = range > 0
3176 ? (slider->sliderPosition - slider->minimum) / range
3177 : 0;
3178
3179 const auto hAlign = foreground->alignment() & Qt::AlignHorizontal_Mask;
3180 const auto vAlign = foreground->alignment() & Qt::AlignVertical_Mask;
3181 const qreal fgW = resolvedWidth(foreground, availableW);
3182 const qreal fgH = resolvedHeight(foreground, availableH);
3183 const qreal fgX = hAlign & Qt::AlignRight
3184 ? grooveRect.left() + foreground->leftMargin() + availableW - fgW
3185 : hAlign & Qt::AlignHCenter
3186 ? grooveRect.left() + foreground->leftMargin() + (availableW - fgW) / 2
3187 : grooveRect.left() + foreground->leftMargin();
3188 const qreal fgY = vAlign & Qt::AlignBottom
3189 ? grooveRect.top() + foreground->topMargin() + availableH - fgH
3190 : vAlign & Qt::AlignVCenter
3191 ? grooveRect.top() + foreground->topMargin() + (availableH - fgH) / 2
3192 : grooveRect.top() + foreground->topMargin();
3193
3194 const qreal minW = foreground->minimumWidth();
3195 QRectF trackRect;
3196 if (isHorizontal) {
3197 const qreal trackW = foreground->fillWidth()
3198 ? minW + ratio * (fgW - minW)
3199 : ratio * fgW;
3200 const qreal trackX = slider->upsideDown ? fgX + (fgW - trackW) : fgX;
3201 trackRect = QRectF(trackX, fgY, trackW, fgH);
3202 } else {
3203 const qreal trackH = foreground->fillHeight()
3204 ? minW + ratio * (fgH - minW)
3205 : ratio * fgH;
3206 const qreal trackY = fgY
3207 + (1.0 - ratio) * (foreground->fillHeight() ? fgH - minW : fgH);
3208 trackRect = QRectF(fgX, trackY, fgW, trackH);
3209 }
3210 // The track is the groove's foreground child, so it inherits the
3211 // indicator's transform.
3212 const QRect foregroundBox = visualRect(
3213 opt->direction, grooveRect, QRectF(fgX, fgY, fgW, fgH).toAlignedRect());
3214 QPainterStateGuard stateGuard(p);
3215 if (applyDelegateTransform(p, indicator, grooveRect)
3216 && applyDelegateTransform(p, foreground, foregroundBox)) {
3217 drawStyledItemContents(
3218 foreground,
3219 visualRect(opt->direction, grooveRect, trackRect.toAlignedRect()), p);
3220 }
3221 }
3222 }
3223
3224 // handle
3225 if (slider->subControls & SC_SliderHandle) {
3226 QStyleOptionSlider handleOpt(*slider);
3227 handleOpt.rect = subControlRect(CC_Slider, opt, SC_SliderHandle, w);
3228 r.drawHandle(handleOpt.rect, p);
3229 }
3230 return;
3231 }
3232 break;
3233#endif // QT_CONFIG(slider)
3234#if QT_CONFIG(dial)
3235 case CC_Dial:
3236 if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3237 const auto r = d->resolve(w, QQStyleKitReader::ControlType::Dial, dial->state);
3238 if (!r.isValid())
3239 break;
3240 const QRectF backgroundRect = QRectF(opt->rect).marginsRemoved(r.metrics->margins);
3241 r.drawBackground(backgroundRect, p);
3242
3243 const auto *handle = r.handle();
3244 if (handle && handle->visible() && handle->opacity() > 0) {
3245 QPainterStateGuard stateGuard(p);
3246 p->translate(backgroundRect.center());
3247 p->rotate(dialAngle(dial));
3248 p->translate(dialHandleOffset(backgroundRect, handle));
3249 r.drawHandle(QRectF(-handle->width() / 2, -handle->height() / 2, handle->width(),
3250 handle->height()),
3251 p);
3252 }
3253 return;
3254 }
3255 break;
3256#endif // QT_CONFIG(dial)
3257#if QT_CONFIG(combobox)
3258 case CC_ComboBox:
3259 if (const QStyleOptionComboBox *combo =
3260 qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
3261 // background
3262 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ComboBox, combo->state);
3263 if (!r.isValid())
3264 break;
3265 QRect frameRect = subControlRect(CC_ComboBox, opt, SC_ComboBoxFrame, w);
3266 r.drawBackground(frameRect, p);
3267
3268 // indicator
3269 if (combo->subControls & SC_ComboBoxArrow) {
3270 QStyleOptionComboBox indicatorOpt(*combo);
3271 indicatorOpt.rect = subControlRect(CC_ComboBox, opt, SC_ComboBoxArrow, w);
3272 proxy()->drawPrimitive(PE_IndicatorArrowDown, &indicatorOpt, p, w);
3273 }
3274
3275 // The editable combobox paints its own line edit using the QPalette::Text role
3276 // for the text color, so update that color in the palette
3277 if (auto *cb = qobject_cast<const QComboBox *>(w); cb && cb->isEditable()) {
3278 if (const auto *txt = r.text(); txt && txt->isDefined(QQSK::Property::Color)) {
3279 QPalette stylePalette;
3280 stylePalette.setColor(QPalette::Text, txt->color());
3281 d->setStylePalette(cb->lineEdit(), stylePalette);
3282 }
3283 }
3284 return;
3285 }
3286 break;
3287#endif // QT_CONFIG(combobox)
3288#if QT_CONFIG(spinbox)
3289 case CC_SpinBox:
3290 if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
3291 const auto r = d->resolve(w, QQStyleKitReader::ControlType::SpinBox, spin->state);
3292 if (!r.isValid())
3293 break;
3294 QRect frameRect = opt->rect.marginsRemoved(r.metrics->margins);
3295 // background
3296 r.drawBackground(frameRect, p);
3297 // up/down buttons
3298 if (spin->subControls & SC_SpinBoxUp) {
3299 QStyleOptionSpinBox upOpt(*spin);
3300 upOpt.rect = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w);
3301 proxy()->drawPrimitive(PE_IndicatorSpinUp, &upOpt, p, w);
3302 }
3303 if (spin->subControls & SC_SpinBoxDown) {
3304 QStyleOptionSpinBox downOpt(*spin);
3305 downOpt.rect = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w);
3306 proxy()->drawPrimitive(PE_IndicatorSpinDown, &downOpt, p, w);
3307 }
3308 // The spinbox line edit paints its text using the QPalette::Text role,
3309 // so update that color in the palette
3310 if (auto *sb = qobject_cast<const QSpinBox *>(w)) {
3311 if (const auto *txt = r.text(); txt && txt->isDefined(QQSK::Property::Color)) {
3312 QLineEdit *lineEdit = sb->findChild<QLineEdit *>();
3313 if (lineEdit) {
3314 QPalette p = lineEdit->palette();
3315 if (p.color(QPalette::Text) != txt->color()) {
3316 p.setColor(QPalette::Text, txt->color());
3317 lineEdit->setPalette(p);
3318 }
3319 }
3320 }
3321 }
3322 return;
3323 }
3324 break;
3325#endif // QT_CONFIG(spinbox)
3326#if QT_CONFIG(groupbox)
3327 case CC_GroupBox:
3328 if (const QStyleOptionGroupBox *groupBox =
3329 qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
3330 // FIXME: Resolve only after querying the sub-control rects,
3331 // as these layout queries can invalidate r.metrics
3332 const QRect frameRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxFrame, w);
3333 const QRect titleRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w);
3334 const auto r = d->resolve(w, QQStyleKitReader::ControlType::GroupBox, groupBox->state);
3335 if (!r.isValid())
3336 break;
3337
3338 // background/frame
3339 if (groupBox->subControls & SC_GroupBoxFrame) {
3340 QStyleOptionFrame frameOpt;
3341 frameOpt.QStyleOption::operator=(*groupBox);
3342 frameOpt.rect = frameRect;
3343 drawPrimitive(PE_FrameGroupBox, &frameOpt, p, w);
3344 }
3345
3346 // title
3347 if (groupBox->subControls & SC_GroupBoxLabel && !groupBox->text.isEmpty()) {
3348 const uint textFlags = styleHint(SH_UnderlineShortcut, opt, w)
3349 ? Qt::TextShowMnemonic : Qt::TextHideMnemonic;
3350 r.drawText(titleRect.marginsRemoved(r.metrics->textPadding), groupBox->text,
3351 textFlags, p, Qt::AlignLeft | Qt::AlignVCenter);
3352 }
3353 // don't draw checkmark as the Controls style doesn't draw it
3354 // and StyleKit doesn't provide a way to style it
3355 return;
3356 }
3357 break;
3358#endif // QT_CONFIG(groupbox)
3359#if QT_CONFIG(scrollbar)
3360 case CC_ScrollBar:
3361 if (const auto *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3362 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ScrollBar,
3363 scrollbar->state);
3364 if (!r.isValid())
3365 break;
3366
3367 // background = groove
3368 if (scrollbar->subControls & SC_ScrollBarGroove) {
3369 QRect backgroundRect = proxy()->subControlRect(
3370 CC_ScrollBar, opt, SC_ScrollBarGroove, w);
3371 r.drawBackground(backgroundRect, p);
3372 }
3373
3374 // TODO: increase button
3375 // TODO: decrease button
3376
3377 // slider = indicator
3378 if (scrollbar->subControls & SC_ScrollBarSlider) {
3379 QStyleOptionSlider newScrollbar(*scrollbar);
3380 newScrollbar.rect = proxy()->subControlRect(
3381 CC_ScrollBar, opt, SC_ScrollBarSlider, w);
3382 proxy()->drawControl(CE_ScrollBarSlider, &newScrollbar, p, w);
3383 }
3384 return;
3385 }
3386 break;
3387#endif // QT_CONFIG(scrollbar)
3388#if QT_CONFIG(toolbutton)
3389 case CC_ToolButton:
3390 if (const QStyleOptionToolButton *tool =
3391 qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
3392 const auto r = d->resolve(w, QQStyleKitReader::ControlType::ToolButton, tool->state);
3393 if (!r.isValid())
3394 break;
3395
3396 // background
3397 r.drawBackground(opt->rect, p);
3398
3399 // menu arrow indicator
3400 if ((tool->features
3401 & (QStyleOptionToolButton::MenuButtonPopup | QStyleOptionToolButton::PopupDelay))
3402 == QStyleOptionToolButton::MenuButtonPopup
3403 && (tool->subControls & SC_ToolButtonMenu)) {
3404 const QRect menuRect = subControlRect(CC_ToolButton, opt, SC_ToolButtonMenu, w);
3405 r.drawIndicator(menuRect, p);
3406 }
3407
3408 // label
3409 State bflags = tool->state & ~State_Sunken;
3410 if (bflags & State_AutoRaise) {
3411 if (!(bflags & State_MouseOver) || !(bflags & State_Enabled))
3412 bflags &= ~State_Raised;
3413 }
3414 if (tool->state & State_Sunken && tool->activeSubControls & SC_ToolButton)
3415 bflags |= State_Sunken;
3416 QStyleOptionToolButton label = *tool;
3417 label.state = bflags;
3418 label.rect = subControlRect(CC_ToolButton, opt, SC_ToolButton, w);
3419 proxy()->drawControl(CE_ToolButtonLabel, &label, p, w);
3420 return;
3421 }
3422 break;
3423#endif // QT_CONFIG(toolbutton)
3424 default:
3425 break;
3426 }
3427 QCommonStyle::drawComplexControl(cc, opt, p, w);
3428}
3429
3430/*! \reimp */
3431QStyle::SubControl QStyleKitStyle::hitTestComplexControl(ComplexControl cc,
3432 const QStyleOptionComplex *opt,
3433 const QPoint &pt, const QWidget *w) const
3434{
3435 return QCommonStyle::hitTestComplexControl(cc, opt, pt, w);
3436}
3437
3438/*! \reimp */
3439QRect QStyleKitStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt,
3440 SubControl sc, const QWidget *w) const
3441{
3442 using QtPrivate::qSaturateRound;
3443 Q_D(const QStyleKitStyle);
3444
3445 switch (cc) {
3446#if QT_CONFIG(slider)
3447 case CC_Slider:
3448 if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3449 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Slider,
3450 opt->state);
3451 if (!resolved.isValid())
3452 break;
3453 const auto &metrics = *resolved.metrics;
3454 const bool horizontal = slider->orientation == Qt::Horizontal;
3455 QRect contentsRect = opt->rect
3456 .marginsRemoved(metrics.margins)
3457 .marginsRemoved(metrics.padding);
3458
3459 const auto *indicator = resolved.indicator();
3460 if (!indicator)
3461 return contentsRect;
3462 switch (sc) {
3463 case SC_SliderGroove: {
3464 const auto availableW = contentsRect.width()
3465 - indicator->leftMargin() - indicator->rightMargin();
3466 const auto availableH = contentsRect.height()
3467 - indicator->topMargin() - indicator->bottomMargin();
3468 const qreal grooveW = resolvedWidth(indicator, availableW);
3469 const qreal grooveH = resolvedHeight(indicator, availableH);
3470
3471 QRectF grooveRect(0, 0, grooveW, grooveH);
3472 const uint rawHAlign = indicator->alignment() & Qt::AlignHorizontal_Mask;
3473 const uint rawVAlign = indicator->alignment() & Qt::AlignVertical_Mask;
3474 const uint hAlign = rawHAlign
3475 ? static_cast<Qt::Alignment>(rawHAlign)
3476 : Qt::AlignLeft;
3477 const uint vAlign = rawVAlign
3478 ? static_cast<Qt::Alignment>(rawVAlign)
3479 : Qt::AlignVCenter;
3480
3481 if (hAlign & Qt::AlignLeft) {
3482 grooveRect.moveLeft(contentsRect.x() + indicator->leftMargin());
3483 } else if (hAlign & Qt::AlignHCenter) {
3484 const qreal availableWidth = contentsRect.width()
3485 - indicator->leftMargin() - indicator->rightMargin();
3486 grooveRect.moveLeft(contentsRect.x() + indicator->leftMargin()
3487 + (availableWidth - grooveW) / 2.0);
3488 } else {
3489 grooveRect.moveLeft(contentsRect.x() + contentsRect.width()
3490 - indicator->rightMargin() - grooveW);
3491 }
3492
3493 if (vAlign & Qt::AlignTop) {
3494 grooveRect.moveTop(contentsRect.y() + indicator->topMargin());
3495 } else if (vAlign & Qt::AlignVCenter) {
3496 const qreal availableHeight = contentsRect.height()
3497 - indicator->topMargin() - indicator->bottomMargin();
3498 grooveRect.moveTop(contentsRect.y()
3499 + indicator->topMargin()
3500 + (availableHeight - grooveH) / 2.0);
3501 } else {
3502 grooveRect.moveTop(contentsRect.y()
3503 + contentsRect.height()
3504 - indicator->bottomMargin() - grooveH);
3505 }
3506 return visualRect(opt->direction, opt->rect, grooveRect.toAlignedRect());
3507 }
3508 case SC_SliderHandle: {
3509 const auto *handle = resolved.handle();
3510 if (!handle || !handle->visible())
3511 return contentsRect;
3512
3513 const qreal handleW = resolvedWidth(
3514 handle, contentsRect.width() - handle->leftMargin() - handle->rightMargin());
3515 const qreal handleH = resolvedHeight(
3516 handle, contentsRect.height() - handle->topMargin() - handle->bottomMargin());
3517 QRectF handleRect(0, 0, handleW, handleH);
3518 if (horizontal) {
3519 const int range = qSaturateRound(contentsRect.width()
3520 - handle->leftMargin() - handle->rightMargin() - handleW);
3521 const int sliderPos = QStyle::sliderPositionFromValue(
3522 slider->minimum, slider->maximum, slider->sliderPosition, range,
3523 slider->upsideDown);
3524 handleRect.moveLeft(contentsRect.x() + handle->leftMargin() + sliderPos);
3525 handleRect.moveTop(contentsRect.y()
3526 + handle->topMargin() - handle->bottomMargin()
3527 + (contentsRect.height() - handleH) / 2.0);
3528 } else {
3529 const int range = qSaturateRound(contentsRect.height()
3530 - handle->topMargin() - handle->bottomMargin() - handleH);
3531 const int sliderPos = QStyle::sliderPositionFromValue(
3532 slider->minimum, slider->maximum, slider->sliderPosition, range,
3533 slider->upsideDown);
3534 handleRect.moveLeft(contentsRect.x()
3535 + handle->leftMargin() - handle->rightMargin()
3536 + (contentsRect.width() - handleW) / 2.0);
3537 handleRect.moveTop(contentsRect.y() + handle->topMargin() + sliderPos);
3538 }
3539 return visualRect(opt->direction, opt->rect, handleRect.toAlignedRect());
3540 }
3541 default:
3542 break;
3543 }
3544 }
3545 break;
3546#endif // QT_CONFIG(slider)
3547#if QT_CONFIG(dial)
3548 case CC_Dial:
3549 if (const QStyleOptionSlider *dial = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3550 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Dial, opt->state);
3551 if (!resolved.isValid())
3552 break;
3553 const auto &metrics = *resolved.metrics;
3554 const QRectF backgroundRect(opt->rect.marginsRemoved(metrics.margins));
3555 if (sc == SC_DialGroove)
3556 return visualRect(opt->direction, opt->rect, backgroundRect.toAlignedRect());
3557 if (sc != SC_DialHandle) {
3558 return sc == SC_DialTickmarks
3559 ? QRect() : QRectF(opt->rect.marginsRemoved(metrics.padding)).toAlignedRect();
3560 }
3561
3562 const auto *handle = resolved.handle();
3563 if (!handle)
3564 return QRect();
3565 const QPointF offset = dialHandleOffset(backgroundRect, handle);
3566 const QPointF center = backgroundRect.center()
3567 + QTransform().rotate(dialAngle(dial)).map(offset);
3568 const QRectF handleRect(center.x() - handle->width() / 2,
3569 center.y() - handle->height() / 2,
3570 handle->width(), handle->height());
3571 return visualRect(opt->direction, opt->rect, handleRect.toAlignedRect());
3572 }
3573 break;
3574#endif // QT_CONFIG(dial)
3575#if QT_CONFIG(combobox)
3576 case CC_ComboBox:
3577 if (const QStyleOptionComboBox *combo =
3578 qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
3579 const auto r = d->resolveLayout(QQStyleKitReader::ControlType::ComboBox, combo->state);
3580 if (!r.isValid())
3581 break;
3582 const auto &metrics = *r.metrics;
3583 QRect frameRect = opt->rect.marginsRemoved(metrics.margins);
3584 switch (sc) {
3585 case SC_ComboBoxFrame:
3586 return visualRect(opt->direction, opt->rect, frameRect);
3587 case SC_ComboBoxEditField: {
3588 QRect contentsRect = frameRect.marginsRemoved(metrics.padding);
3589 QRect indicatorRect = subControlRect(CC_ComboBox, opt, SC_ComboBoxArrow, w);
3590 // Map back to logical coordinates, the result is mirrored below
3591 indicatorRect = visualRect(opt->direction, opt->rect, indicatorRect);
3592 const int spacing = metrics.spacing;
3593 const auto *indicator = r.indicator();
3594 const uint indicatorAlign = indicator
3595 ? resolvedAlignment(indicator->alignment(), Qt::AlignRight, Qt::AlignVCenter)
3596 : uint(Qt::AlignRight | Qt::AlignVCenter);
3597 if (indicatorAlign & Qt::AlignLeft) {
3598 contentsRect.setLeft(indicatorRect.right() + spacing);
3599 } else if (indicatorAlign & Qt::AlignRight) {
3600 contentsRect.setRight(indicatorRect.left() - spacing);
3601 }
3602 return visualRect(opt->direction, opt->rect, contentsRect);
3603 }
3604 case SC_ComboBoxArrow: {
3605 QRect contentsRect = frameRect.marginsRemoved(metrics.padding);
3606 const auto *indicator = r.indicator();
3607 if (!indicator || !indicator->visible())
3608 return QRect();
3609
3610 return visualRect(opt->direction, opt->rect,
3611 delegateRect(indicator, contentsRect, Qt::AlignRight,
3612 Qt::AlignVCenter));
3613 }
3614 case SC_ComboBoxListBoxPopup: {
3615 QRect popupRect = opt->rect;
3616 popupRect.setTop(opt->rect.bottom());
3617 return visualRect(opt->direction, opt->rect, popupRect);
3618 }
3619 default:
3620 break;
3621 }
3622 }
3623 break;
3624#endif // QT_CONFIG(combobox)
3625#if QT_CONFIG(spinbox)
3626 case CC_SpinBox:
3627 if (const QStyleOptionSpinBox *spinBox =
3628 qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
3629 const auto r = d->resolveLayout(QQStyleKitReader::ControlType::SpinBox, spinBox->state);
3630 if (!r.isValid())
3631 break;
3632 const auto &metrics = *r.metrics;
3633 QRect frameRect = opt->rect.marginsRemoved(metrics.margins);
3634 QRect contentsRect = frameRect.marginsRemoved(metrics.padding);
3635 switch (sc) {
3636 case SC_SpinBoxFrame:
3637 return visualRect(opt->direction, opt->rect, frameRect);
3638 case SC_SpinBoxEditField: {
3639 QRect upIndicatorRect = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w);
3640 QRect downIndicatorRect = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w);
3641 // Map back to logical coordinates, the result is mirrored below
3642 upIndicatorRect = visualRect(opt->direction, opt->rect, upIndicatorRect);
3643 downIndicatorRect = visualRect(opt->direction, opt->rect, downIndicatorRect);
3644 const int spacing = metrics.spacing;
3645 const auto *upIndicator = r.indicator() ? r.indicator()->first() : nullptr;
3646 const auto *downIndicator = r.indicator() ? r.indicator()->second() : nullptr;
3647 const bool hasUpIndicator = upIndicator && upIndicator->visible();
3648 const bool hasDownIndicator = downIndicator && downIndicator->visible();
3649 const uint upAlign = hasUpIndicator
3650 ? resolvedAlignment(upIndicator->alignment(), Qt::AlignLeft, Qt::AlignVCenter)
3651 : uint(Qt::AlignLeft | Qt::AlignVCenter);
3652 const uint downAlign = hasDownIndicator
3653 ? resolvedAlignment(downIndicator->alignment(), Qt::AlignLeft, Qt::AlignVCenter)
3654 : uint(Qt::AlignLeft | Qt::AlignVCenter);
3655 if (hasUpIndicator && hasDownIndicator) {
3656 if ((upAlign & Qt::AlignLeft) && (downAlign & Qt::AlignRight)) {
3657 contentsRect.setLeft(upIndicatorRect.right() + spacing);
3658 contentsRect.setRight(downIndicatorRect.left() - spacing);
3659 } else if ((upAlign & Qt::AlignRight) && (downAlign & Qt::AlignLeft)) {
3660 contentsRect.setRight(upIndicatorRect.left() - spacing);
3661 contentsRect.setLeft(downIndicatorRect.right() + spacing);
3662 }
3663 } else if (hasUpIndicator) {
3664 if (upAlign & Qt::AlignLeft) {
3665 contentsRect.setLeft(upIndicatorRect.right() + spacing);
3666 } else if (upAlign & Qt::AlignRight) {
3667 contentsRect.setRight(upIndicatorRect.left() - spacing);
3668 }
3669 } else if (hasDownIndicator) {
3670 if (downAlign & Qt::AlignLeft) {
3671 contentsRect.setLeft(downIndicatorRect.right() + spacing);
3672 } else if (downAlign & Qt::AlignRight) {
3673 contentsRect.setRight(downIndicatorRect.left() - spacing);
3674 }
3675 }
3676 return visualRect(opt->direction, opt->rect, contentsRect);
3677 }
3678 case SC_SpinBoxUp: {
3679 const auto *upIndicator = r.indicator() ? r.indicator()->first() : nullptr;
3680 if (!upIndicator || !upIndicator->visible())
3681 return contentsRect;
3682
3683 return visualRect(opt->direction, opt->rect,
3684 delegateRect(upIndicator, contentsRect, Qt::AlignLeft,
3685 Qt::AlignVCenter));
3686 }
3687 case SC_SpinBoxDown: {
3688 const auto *downIndicator = r.indicator() ? r.indicator()->second() : nullptr;
3689 if (!downIndicator || !downIndicator->visible())
3690 return frameRect;
3691
3692 return visualRect(opt->direction, opt->rect,
3693 delegateRect(downIndicator, contentsRect, Qt::AlignLeft,
3694 Qt::AlignVCenter));
3695 }
3696 default:
3697 break;
3698 }
3699 }
3700 break;
3701#endif // QT_CONFIG(spinbox)
3702#if QT_CONFIG(groupbox)
3703 case CC_GroupBox:
3704 if (const QStyleOptionGroupBox *groupBox =
3705 qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
3706 const auto r = d->resolveLayout(QQStyleKitReader::ControlType::GroupBox,
3707 groupBox->state);
3708 if (!r.isValid())
3709 break;
3710 const auto &metrics = *r.metrics;
3711 QRect frameRect = opt->rect.marginsRemoved(metrics.margins);
3712 switch (sc) {
3713 case SC_GroupBoxFrame:
3714 return visualRect(opt->direction, opt->rect, frameRect);
3715 case SC_GroupBoxLabel: {
3716 const int fontHeight = opt->fontMetrics.height();
3717 const int labelHeight = metrics.textPadding.top()
3718 + fontHeight + metrics.textPadding.bottom();
3719 const QRect labelContainer(opt->rect.left(), opt->rect.top(), opt->rect.width(),
3720 labelHeight);
3721 return visualRect(opt->direction, opt->rect, labelContainer);
3722 }
3723 case SC_GroupBoxCheckBox: {
3724 // The controls style doesn't draw the checkbox, so we don't return a rect for it
3725 return QRect();
3726 }
3727 case SC_GroupBoxContents: {
3728 const auto labelHeight = subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w)
3729 .height();
3730 const auto offset = metrics.padding.top()
3731 + qMax(metrics.margins.top(), labelHeight + metrics.spacing);
3732 QRect contentsRect(
3733 opt->rect.left() + metrics.padding.left(), opt->rect.top() + offset,
3734 opt->rect.width() - metrics.padding.left() - metrics.padding.right(),
3735 opt->rect.bottom() - opt->rect.top() - offset - metrics.padding.bottom());
3736 return visualRect(opt->direction, opt->rect, contentsRect);
3737 }
3738 default:
3739 break;
3740 }
3741 }
3742 break;
3743#endif // QT_CONFIG(groupbox)
3744#if QT_CONFIG(scrollbar)
3745 case CC_ScrollBar:
3746 if (const auto *scrollbar = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3747 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ScrollBar,
3748 opt->state);
3749 if (!resolved.isValid())
3750 break;
3751 const auto &metrics = *resolved.metrics;
3752 const bool horizontal = scrollbar->orientation == Qt::Horizontal;
3753 const QRectF grooveRect = opt->rect.marginsRemoved(metrics.margins);
3754
3755 switch (sc) {
3756 // TODO: support up/down buttons
3757 case SC_ScrollBarAddLine:
3758 case SC_ScrollBarSubLine:
3759 case SC_ScrollBarSubPage:
3760 case SC_ScrollBarAddPage:
3761 return QRect();
3762 case SC_ScrollBarGroove:
3763 return visualRect(opt->direction, opt->rect, grooveRect.toAlignedRect());
3764 case SC_ScrollBarSlider: {
3765 const auto *indicator = resolved.indicator();
3766 if (!indicator || !indicator->visible())
3767 return QRect();
3768 const QRectF contentsRect = grooveRect.marginsRemoved(metrics.padding);
3769
3770 const qreal availableW = contentsRect.width()
3771 - indicator->leftMargin() - indicator->rightMargin();
3772 const qreal availableH = contentsRect.height()
3773 - indicator->topMargin() - indicator->bottomMargin();
3774
3775 const int totalRange = scrollbar->maximum
3776 - scrollbar->minimum + scrollbar->pageStep;
3777 const qreal ratio = totalRange > 0 ? qreal(scrollbar->pageStep) / totalRange : 1.0;
3778
3779 QRectF sliderRect;
3780 if (horizontal) {
3781 const qreal sliderW = qMax(
3782 qreal(metrics.indicatorImplicitSize.width()), availableW * ratio);
3783 const qreal sliderH = resolvedHeight(indicator, availableH);
3784 const qreal travelRange = qMax(0.0, availableW - sliderW);
3785 const int sliderPos = QStyle::sliderPositionFromValue(
3786 scrollbar->minimum, scrollbar->maximum, scrollbar->sliderPosition,
3787 int(travelRange), scrollbar->upsideDown);
3788 sliderRect = QRectF(
3789 contentsRect.x() + indicator->leftMargin() + sliderPos,
3790 contentsRect.y() + indicator->topMargin() + (availableH - sliderH) / 2.0,
3791 sliderW, sliderH);
3792 } else {
3793 const qreal sliderH = qMax(
3794 qreal(metrics.indicatorImplicitSize.width()), availableH * ratio);
3795 const qreal sliderW = resolvedWidth(indicator, availableW);
3796 const qreal travelRange = qMax(0.0, availableH - sliderH);
3797 const int sliderPos = QStyle::sliderPositionFromValue(
3798 scrollbar->minimum, scrollbar->maximum, scrollbar->sliderPosition,
3799 int(travelRange), scrollbar->upsideDown);
3800 sliderRect = QRectF(
3801 contentsRect.x() + indicator->leftMargin() + (availableW - sliderW) / 2.0,
3802 contentsRect.y() + indicator->topMargin() + sliderPos, sliderW, sliderH);
3803 }
3804 return visualRect(opt->direction, opt->rect, sliderRect.toAlignedRect());
3805 }
3806 default:
3807 break;
3808 }
3809 }
3810 break;
3811#endif // QT_CONFIG(scrollbar)
3812#if QT_CONFIG(toolbutton)
3813 case CC_ToolButton:
3814 if (const auto *tool = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
3815 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ToolButton,
3816 opt->state);
3817 if (!resolved.isValid())
3818 break;
3819 const auto &metrics = *resolved.metrics;
3820 QRect frameRect = opt->rect.marginsRemoved(metrics.margins);
3821 switch (sc) {
3822 case SC_ToolButton: {
3823 QRect contentsRect = frameRect.marginsRemoved(metrics.padding);
3824 const bool hasMenuButton =
3825 (tool->features & QStyleOptionToolButton::MenuButtonPopup) != 0;
3826 const auto *indicator = resolved.indicator();
3827 if (hasMenuButton && indicator && indicator->visible()) {
3828 QRect menuRect = subControlRect(CC_ToolButton, opt, SC_ToolButtonMenu, w);
3829 // Map back to logical coordinates, the result is mirrored below
3830 menuRect = visualRect(opt->direction, opt->rect, menuRect);
3831 const int spacing = metrics.spacing;
3832 const uint indicatorAlign = resolvedAlignment(indicator->alignment(),
3833 Qt::AlignRight, Qt::AlignVCenter);
3834 if (indicatorAlign & Qt::AlignLeft)
3835 contentsRect.setLeft(menuRect.right() + spacing);
3836 else if (indicatorAlign & Qt::AlignRight)
3837 contentsRect.setRight(menuRect.left() - spacing);
3838 }
3839 return visualRect(opt->direction, opt->rect, contentsRect);
3840 }
3841 case SC_ToolButtonMenu: {
3842 QRect contentsRect = frameRect.marginsRemoved(metrics.padding);
3843 if ((tool->features
3844 & (QStyleOptionToolButton::MenuButtonPopup
3845 | QStyleOptionToolButton::PopupDelay))
3846 != QStyleOptionToolButton::MenuButtonPopup) {
3847 break;
3848 }
3849
3850 const auto *indicator = resolved.indicator();
3851 if (!indicator || !indicator->visible())
3852 return QRect();
3853
3854 return visualRect(opt->direction, opt->rect,
3855 delegateRect(indicator, contentsRect, Qt::AlignRight,
3856 Qt::AlignVCenter));
3857 }
3858 default:
3859 break;
3860 }
3861 }
3862 break;
3863#endif // QT_CONFIG(toolbutton)
3864 default:
3865 break;
3866 }
3867 return QCommonStyle::subControlRect(cc, opt, sc, w);
3868}
3869
3870/*! \reimp */
3871QSize QStyleKitStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
3872 const QSize &contentsSize, const QWidget *widget) const
3873{
3874 Q_D(const QStyleKitStyle);
3875
3876 switch (ct) {
3877#if QT_CONFIG(pushbutton)
3878 case CT_PushButton:
3879#endif
3880#if QT_CONFIG(toolbutton)
3881 case CT_ToolButton: {
3882 auto controlType = QQStyleKitReader::ControlType::ToolButton;
3883 if (const auto *buttonOpt = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3884 controlType = (buttonOpt->features & QStyleOptionButton::Flat)
3885 ? QQStyleKitReader::ControlType::FlatButton
3886 : QQStyleKitReader::ControlType::Button;
3887 }
3888 const auto resolved = d->resolveLayout(controlType, opt->state);
3889 if (!resolved.isValid())
3890 break;
3891
3892 const auto &metrics = *resolved.metrics;
3893 const QSize contentSize = contentsSize
3894 + QSize(metrics.padding.left() + metrics.padding.right(),
3895 metrics.padding.top() + metrics.padding.bottom())
3896 + QSize(metrics.textPadding.left() + metrics.textPadding.right(),
3897 metrics.textPadding.top() + metrics.textPadding.bottom());
3898 const QSize bgSize = metrics.bgImplicitSize
3899 + QSize(metrics.margins.left() + metrics.margins.right(),
3900 metrics.margins.top() + metrics.margins.bottom());
3901 return contentSize.expandedTo(bgSize);
3902 }
3903#endif
3904 case CT_CheckBox:
3905 case CT_RadioButton:
3906 if (const auto *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3907 const auto controlType = ct == CT_CheckBox ? QQStyleKitReader::ControlType::CheckBox
3908 : QQStyleKitReader::ControlType::RadioButton;
3909 const auto resolved = d->resolveLayout(controlType, opt->state);
3910 if (!resolved.isValid())
3911 break;
3912 const auto &metrics = *resolved.metrics;
3913 const QSize textSize = opt->fontMetrics.size(Qt::TextShowMnemonic, btn->text);
3914 const int bgWidth = metrics.bgImplicitSize.width()
3915 + metrics.margins.left() + metrics.margins.right();
3916 const int bgHeight = metrics.bgImplicitSize.height()
3917 + metrics.margins.top() + metrics.margins.bottom();
3918 const int contentWidth = std::max(textSize.width(), contentsSize.width())
3919 + metrics.padding.left() + metrics.padding.right() + metrics.textPadding.left()
3920 + metrics.textPadding.right();
3921 const int contentHeight = std::max(textSize.height(), contentsSize.height())
3922 + metrics.padding.top() + metrics.padding.bottom() + metrics.textPadding.top()
3923 + metrics.textPadding.bottom();
3924 const int indicatorWidth = metrics.indicatorImplicitSize.width()
3925 + metrics.indicatorMargins.left() + metrics.indicatorMargins.right();
3926 const int indicatorHeight = metrics.indicatorImplicitSize.height()
3927 + metrics.indicatorMargins.top() + metrics.indicatorMargins.bottom();
3928 return QSize(std::max({ contentWidth + indicatorWidth + metrics.spacing, bgWidth }),
3929 std::max({ contentHeight, indicatorHeight, bgHeight }));
3930 }
3931 break;
3932#if QT_CONFIG(itemviews)
3933 case CT_ItemViewItem:
3934 if (const auto *item = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
3935 const auto resolved = d->resolveLayout(itemViewControlType(opt), opt->state);
3936 if (!resolved.isValid())
3937 break;
3938 const auto &metrics = *resolved.metrics;
3939 const QSize textSize = opt->fontMetrics.size(Qt::TextShowMnemonic, item->text);
3940 const int bgWidth = metrics.bgImplicitSize.width()
3941 + metrics.margins.left() + metrics.margins.right();
3942 const int bgHeight = metrics.bgImplicitSize.height()
3943 + metrics.margins.top() + metrics.margins.bottom();
3944 const int contentWidth = std::max(textSize.width(), contentsSize.width())
3945 + metrics.padding.left() + metrics.padding.right() + metrics.textPadding.left()
3946 + metrics.textPadding.right();
3947 const int contentHeight = std::max(textSize.height(), contentsSize.height())
3948 + metrics.padding.top() + metrics.padding.bottom() + metrics.textPadding.top()
3949 + metrics.textPadding.bottom();
3950 const int indicatorWidth = metrics.indicatorImplicitSize.width()
3951 + metrics.indicatorMargins.left() + metrics.indicatorMargins.right();
3952 const int indicatorHeight = metrics.indicatorImplicitSize.height()
3953 + metrics.indicatorMargins.top() + metrics.indicatorMargins.bottom();
3954 return QSize(std::max({ contentWidth + indicatorWidth + metrics.spacing, bgWidth }),
3955 std::max({ contentHeight, indicatorHeight, bgHeight }));
3956 }
3957 break;
3958#endif // QT_CONFIG(itemviews)
3959 case CT_ProgressBar:
3960 if (qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
3961 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ProgressBar,
3962 opt->state);
3963 if (!resolved.isValid())
3964 break;
3965 const auto &metrics = *resolved.metrics;
3966 const auto indicatorW = metrics.indicatorImplicitSize.width()
3967 + metrics.indicatorMargins.left()
3968 + metrics.indicatorMargins.right();
3969 const auto indicatorH = metrics.indicatorImplicitSize.height()
3970 + metrics.indicatorMargins.top()
3971 + metrics.indicatorMargins.bottom();
3972 const int bgW = metrics.bgImplicitSize.width()
3973 + metrics.margins.left() + metrics.margins.right();
3974 const int bgH = metrics.bgImplicitSize.height()
3975 + metrics.margins.top() + metrics.margins.bottom();
3976 // For progress bar in Controls, the content size is based on the indicator size
3977 const int contentW = indicatorW + metrics.padding.left() + metrics.padding.right();
3978 const int contentH = indicatorH + metrics.padding.top() + metrics.padding.bottom();
3979 return QSize(std::max(contentW, bgW), std::max(contentH, bgH));
3980 }
3981 break;
3982 case CT_Slider:
3983 if (qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3984 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Slider,
3985 opt->state);
3986 if (!resolved.isValid())
3987 break;
3988 const auto &metrics = *resolved.metrics;
3989 // background = indicator = groove + track
3990 const int bgW = std::max(
3991 metrics.padding.left() + metrics.padding.right()
3992 + metrics.indicatorImplicitSize.width()
3993 + metrics.indicatorMargins.left() + metrics.indicatorMargins.right(),
3994 metrics.bgImplicitSize.width() + metrics.margins.left() + metrics.margins.right());
3995 const int bgH = std::max(
3996 metrics.padding.top() + metrics.padding.bottom()
3997 + metrics.indicatorImplicitSize.height()
3998 + metrics.indicatorMargins.top() + metrics.indicatorMargins.bottom(),
3999 metrics.bgImplicitSize.height() + metrics.margins.top() + metrics.margins.bottom());
4000 const int handleW = metrics.handleImplicitSize.width()
4001 + metrics.padding.left()
4002 + metrics.padding.right();
4003 const int handleH = metrics.handleImplicitSize.height()
4004 + metrics.padding.top()
4005 + metrics.padding.bottom();
4006 return QSize(std::max(handleW, bgW), std::max(handleH, bgH));
4007 }
4008 break;
4009#if QT_CONFIG(lineedit)
4010 case CT_LineEdit:
4011 if (const auto *lineEdit = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
4012 QStyleOption lineEditOpt(*lineEdit);
4013 lineEditOpt.state &= ~QStyle::State_Sunken;
4014# if QT_CONFIG(spinbox)
4015 const bool isInSpinBox = widget && qobject_cast<const QSpinBox *>(widget->parent());
4016# else
4017 const bool isInSpinBox = false;
4018# endif
4019 auto controlType = isInSpinBox ? QQStyleKitReader::ControlType::SpinBox
4020 : QQStyleKitReader::ControlType::TextField;
4021 const auto resolved = d->resolveLayout(controlType, lineEditOpt.state);
4022 if (!resolved.isValid())
4023 break;
4024 const auto &metrics = *resolved.metrics;
4025 QSize bgSize(0, 0);
4026 // For spinbox, the line edit doesn't have its own background in the Controls style
4027 if (!isInSpinBox)
4028 bgSize = metrics.bgImplicitSize.grownBy(metrics.margins);
4029 const QSize contentSizeWithPadding = contentsSize
4030 .grownBy(metrics.textPadding)
4031 .grownBy(metrics.padding);
4032 return contentSizeWithPadding.expandedTo(bgSize);
4033 }
4034 break;
4035#endif // QT_CONFIG(lineedit)
4036#if QT_CONFIG(combobox)
4037 case CT_ComboBox:
4038 if (const auto *comboBox = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
4039 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ComboBox,
4040 opt->state);
4041 if (!resolved.isValid())
4042 break;
4043 const auto &metrics = *resolved.metrics;
4044 QSize textSize = opt->fontMetrics.size(
4045 Qt::TextShowMnemonic, comboBox->currentText);
4046 if (!comboBox->currentIcon.isNull()) {
4047 textSize.rwidth() += comboBox->iconSize.width() + metrics.spacing;
4048 textSize.setHeight(qMax(textSize.height(), comboBox->iconSize.height()));
4049 }
4050 const int bgW = metrics.bgImplicitSize.width()
4051 + metrics.margins.left() + metrics.margins.right();
4052 const int bgH = metrics.bgImplicitSize.height()
4053 + metrics.margins.top() + metrics.margins.bottom();
4054 const int contentW = textSize.width()
4055 + metrics.padding.left() + metrics.padding.right()
4056 + metrics.textPadding.left() + metrics.textPadding.right();
4057 const int contentH = textSize.height()
4058 + metrics.padding.top() + metrics.padding.bottom()
4059 + metrics.textPadding.top() + metrics.textPadding.bottom();
4060 const int indicatorW = metrics.indicatorImplicitSize.width()
4061 + metrics.indicatorMargins.left() + metrics.indicatorMargins.right();
4062 const int indicatorH = metrics.indicatorImplicitSize.height()
4063 + metrics.indicatorMargins.top() + metrics.indicatorMargins.bottom();
4064 return QSize(std::max({ contentW + indicatorW + metrics.spacing, bgW }),
4065 std::max({ contentH, indicatorH, bgH }));
4066 }
4067 break;
4068#endif // QT_CONFIG(combobox)
4069#if QT_CONFIG(spinbox)
4070 case CT_SpinBox: {
4071 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::SpinBox, opt->state);
4072 if (!resolved.isValid())
4073 break;
4074 const auto &metrics = *resolved.metrics;
4075 const int bgW = metrics.bgImplicitSize.width()
4076 + metrics.margins.left() + metrics.margins.right();
4077 const int bgH = metrics.bgImplicitSize.height()
4078 + metrics.margins.top() + metrics.margins.bottom();
4079 const int contentW = contentsSize.width()
4080 + metrics.padding.left() + metrics.padding.right()
4081 + metrics.textPadding.left() + metrics.textPadding.right();
4082 const int contentH = contentsSize.height()
4083 + metrics.padding.top() + metrics.padding.bottom()
4084 + metrics.textPadding.top() + metrics.textPadding.bottom();
4085 // TODO: Support vertical layout for spinbox, currently we assume horizontal layout
4086 // TODO: Calculate each indicator (up/down) size separately if they have different sizes in
4087 // the style
4088 const int indicatorW = (metrics.indicatorImplicitSize.width()
4089 + metrics.indicatorMargins.left() + metrics.indicatorMargins.right()) * 2;
4090 const int indicatorH = metrics.indicatorImplicitSize.height()
4091 + metrics.indicatorMargins.top() + metrics.indicatorMargins.bottom();
4092 return QSize(std::max({ contentW + indicatorW + metrics.spacing, bgW }),
4093 std::max({ contentH, indicatorH, bgH }));
4094 }
4095#endif // QT_CONFIG(spinbox)
4096#if QT_CONFIG(tabbar)
4097 case CT_TabBarTab:
4098 if (qstyleoption_cast<const QStyleOptionTab *>(opt)) {
4099 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::TabButton,
4100 opt->state);
4101 if (!resolved.isValid())
4102 break;
4103 const auto &m = *resolved.metrics;
4104 const auto bgSize = m.bgImplicitSize.grownBy(m.margins);
4105 const auto contentSizeWithPadding = contentsSize.grownBy(m.padding + m.textPadding);
4106 return contentSizeWithPadding.expandedTo(bgSize);
4107 }
4108 break;
4109#endif // QT_CONFIG(tabbar)
4110#if QT_CONFIG(tabwidget)
4111 case CT_TabWidget:
4112 if (qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
4113 // TabWidget corresponds to Page
4114 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Page, opt->state);
4115 if (!resolved.isValid())
4116 break;
4117 const auto &m = *resolved.metrics;
4118 const auto bgSize = m.bgImplicitSize.grownBy(m.margins);
4119 const auto contentSizeWithPadding = contentsSize.grownBy(m.padding);
4120 return contentSizeWithPadding.expandedTo(bgSize);
4121 }
4122 break;
4123#endif // QT_CONFIG(tabwidget)
4124#if QT_CONFIG(groupbox)
4125 case CT_GroupBox:
4126 if (const auto *groupBox = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
4127 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::GroupBox,
4128 opt->state);
4129 if (!resolved.isValid())
4130 break;
4131 const auto &metrics = *resolved.metrics;
4132 const QSize bgSize = metrics.bgImplicitSize
4133 + QSize(metrics.margins.left() + metrics.margins.right(),
4134 metrics.margins.top() + metrics.margins.bottom());
4135 const QSize contentSize = contentsSize.grownBy(metrics.padding);
4136 const QSize textSize = opt->fontMetrics
4137 .size(Qt::TextShowMnemonic, groupBox->text)
4138 .grownBy(metrics.textPadding);
4139 return textSize.expandedTo(contentSize).expandedTo(bgSize);
4140 }
4141 break;
4142#endif // QT_CONFIG(groupbox)
4143#if QT_CONFIG(scrollbar)
4144 case CT_ScrollBar:
4145 if (qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
4146 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ScrollBar, opt->state);
4147 if (!resolved.isValid())
4148 break;
4149 const auto &metrics = *resolved.metrics;
4150
4151 const int iH = metrics.indicatorImplicitSize.height()
4152 + metrics.padding.top() + metrics.padding.bottom()
4153 + metrics.indicatorMargins.top() + metrics.indicatorMargins.bottom();
4154 const int iW = metrics.indicatorImplicitSize.width()
4155 + metrics.padding.left() + metrics.padding.right()
4156 + metrics.indicatorMargins.left() + metrics.indicatorMargins.right();
4157 const int bgH = metrics.bgImplicitSize.height()
4158 + metrics.margins.top() + metrics.margins.bottom();
4159 const int bgW = metrics.bgImplicitSize.width()
4160 + metrics.margins.left() + metrics.margins.right();
4161 return QSize(std::max(iW, bgW), std::max(iH, bgH));
4162 }
4163 break;
4164#endif // QT_CONFIG(scrollbar)
4165#if QT_CONFIG(menu)
4166 case CT_MenuItem:
4167 if (const auto *menuItem = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
4168 // The menu dictates the item width
4169 // QMenu uses for PM_MenuHMargin for both left/right paddings,
4170 // so the available width is bgImplicitWidth + margins - 2 * padding.left.
4171 const auto menuType = widget && widget->inherits("QComboBoxPrivateContainer")
4172 ? QQStyleKitReader::ControlType::Popup
4173 : QQStyleKitReader::ControlType::Menu;
4174 const auto menuResolved = d->resolveLayout(menuType, opt->state);
4175 int minMenuW = 0;
4176 if (menuResolved.isValid()) {
4177 const auto &mm = *menuResolved.metrics;
4178 minMenuW = mm.bgImplicitSize.width()
4179 + mm.margins.left() + mm.margins.right() - 2 * mm.padding.left();
4180 }
4181
4182 if (menuItem->menuItemType == QStyleOptionMenuItem::Separator) {
4183 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::MenuSeparator,
4184 opt->state);
4185 if (!resolved.isValid())
4186 break;
4187 const auto &m = *resolved.metrics;
4188 const int bgWidth = m.bgImplicitSize.width()
4189 + m.margins.left() + m.margins.right();
4190 const int bgHeight = m.bgImplicitSize.height()
4191 + m.margins.top() + m.margins.bottom();
4192 return QSize(std::max(bgWidth, minMenuW), bgHeight);
4193 }
4194
4195 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::MenuItem, opt->state);
4196 if (!resolved.isValid())
4197 break;
4198 const auto &m = *resolved.metrics;
4199 const auto *indicator = resolved.indicator();
4200 const auto *first = indicator ? indicator->first() : nullptr;
4201 const auto *second = indicator ? indicator->second() : nullptr;
4202 int indicatorW = 0;
4203 int indicatorH = 0;
4204 using QtPrivate::qSaturateRound;
4205 if (first && menuItem->menuHasCheckableItems) {
4206 indicatorW += qSaturateRound(
4207 first->leftMargin() + first->width() + first->rightMargin()) + m.spacing;
4208 indicatorH = std::max(
4209 qSaturateRound(first->topMargin() + first->bottomMargin() + first->height()),
4210 indicatorH);
4211 }
4212 if (second && menuItem->menuItemType == QStyleOptionMenuItem::SubMenu) {
4213 indicatorW += qSaturateRound(
4214 second->leftMargin() + second->width() + second->rightMargin()) + m.spacing;
4215 indicatorH = std::max(
4216 qSaturateRound(second->topMargin() + second->bottomMargin() + second->height()),
4217 indicatorH);
4218 }
4219 const int bgH = m.bgImplicitSize.height() + m.margins.top() + m.margins.bottom();
4220 const int iconReserved = menuItem->maxIconWidth > 0
4221 ? proxy()->pixelMetric(PM_SmallIconSize, opt, widget) + m.spacing
4222 : 0;
4223 const int contentW = contentsSize.width()
4224 + m.padding.left() + m.padding.right()
4225 + m.textPadding.left() + m.textPadding.right()
4226 + indicatorW + iconReserved;
4227 const int contentH = contentsSize.height()
4228 + m.padding.top() + m.padding.bottom()
4229 + m.textPadding.top() + m.textPadding.bottom();
4230 return QSize(std::max(contentW, minMenuW), std::max({ contentH, indicatorH, bgH }));
4231 }
4232 break;
4233 case CT_Menu: {
4234 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::Menu, opt->state);
4235 if (!resolved.isValid())
4236 break;
4237 const auto &m = *resolved.metrics;
4238 const int height = std::max(contentsSize.height(), m.bgImplicitSize.height())
4239 + m.margins.top() + m.margins.bottom();
4240 return QSize(contentsSize.width(), height);
4241 }
4242#endif // QT_CONFIG(menu)
4243#if QT_CONFIG(menubar)
4244 case CT_MenuBar: {
4245 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::MenuBar, opt->state);
4246 if (!resolved.isValid())
4247 break;
4248 const auto &m = *resolved.metrics;
4249 const int bgWidth = m.bgImplicitSize.width() + m.margins.left() + m.margins.right();
4250 const int bgHeight = m.bgImplicitSize.height() + m.margins.top() + m.margins.bottom();
4251 const int contentW = contentsSize.width() + m.padding.left() + m.padding.right();
4252 const int contentH = contentsSize.height() + m.padding.top() + m.padding.bottom();
4253 return QSize(std::max(contentW, bgWidth), std::max(contentH, bgHeight));
4254 }
4255 case CT_MenuBarItem: {
4256 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::MenuBarItem,
4257 opt->state);
4258 if (!resolved.isValid())
4259 break;
4260 const auto &m = *resolved.metrics;
4261 const int bgWidth = m.bgImplicitSize.width() + m.margins.left() + m.margins.right();
4262 const int bgHeight = m.bgImplicitSize.height() + m.margins.top() + m.margins.bottom();
4263 const int contentW = contentsSize.width()
4264 + m.padding.left() + m.padding.right()
4265 + m.textPadding.left() + m.textPadding.right();
4266 const int contentH = contentsSize.height()
4267 + m.padding.top() + m.padding.bottom()
4268 + m.textPadding.top() + m.textPadding.bottom();
4269 return QSize(std::max(contentW, bgWidth), std::max(contentH, bgHeight));
4270 }
4271#endif // QT_CONFIG(menubar)
4272 default:
4273 break;
4274 }
4275 return QCommonStyle::sizeFromContents(ct, opt, contentsSize, widget);
4276}
4277
4278/*! \reimp */
4279int QStyleKitStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWidget *widget) const
4280{
4281 Q_D(const QStyleKitStyle);
4282 switch (m) {
4283#if QT_CONFIG(menu)
4284 case PM_MenuPanelWidth:
4285 // The panel border is drawn as part of the resolved background (see PE_PanelMenu);
4286 return 0;
4287 case PM_MenuTearoffHeight:
4288 case PM_MenuScrollerHeight:
4289 return 0;
4290 case PM_MenuHMargin:
4291 case PM_MenuVMargin: {
4292 const auto controlType = widget && widget->inherits("QComboBoxPrivateContainer")
4293 ? QQStyleKitReader::ControlType::Popup
4294 : QQStyleKitReader::ControlType::Menu;
4295 const auto resolved = d->resolveLayout(controlType, opt ? opt->state : QStyle::State_None);
4296 if (!resolved.isValid())
4297 break;
4298 return m == PM_MenuHMargin ? resolved.metrics->padding.left()
4299 : resolved.metrics->padding.top();
4300 }
4301#endif
4302#if QT_CONFIG(menubar)
4303 case PM_MenuBarItemSpacing: {
4304 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::MenuBarItem,
4305 opt ? opt->state : QStyle::State_None);
4306 if (resolved.isValid())
4307 return resolved.metrics->spacing;
4308 break;
4309 }
4310#endif
4311#if QT_CONFIG(tooltip)
4312 case PM_ToolTipLabelFrameWidth: {
4313 // QTipLabel adds 1 to this and applies it uniformly on all sides
4314 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ToolTip,
4315 opt ? opt->state : QStyle::State_None);
4316 if (!resolved.isValid())
4317 break;
4318 const auto *m = resolved.metrics;
4319 return qMax(0, m->margins.left() + m->padding.left() + m->textPadding.left() - 1);
4320 }
4321#endif
4322#if QT_CONFIG(toolbar)
4323 case PM_ToolBarFrameWidth:
4324 // The frame is folded into the resolved background/margins (see CE_ToolBar);
4325 return 0;
4326 case PM_ToolBarItemMargin: {
4327 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ToolBar,
4328 opt ? opt->state : QStyle::State_None);
4329 if (!resolved.isValid())
4330 break;
4331 return resolved.metrics->padding.left();
4332 }
4333 case PM_ToolBarItemSpacing: {
4334 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ToolBar,
4335 opt ? opt->state : QStyle::State_None);
4336 if (resolved.isValid())
4337 return resolved.metrics->spacing;
4338 break;
4339 }
4340 case PM_ToolBarHandleExtent: {
4341 // The only lever available to honor the style's background width/height
4342 // QToolBarLayout uses this to calculate the minimum size of the toolbar
4343 const auto resolved = d->resolveLayout(QQStyleKitReader::ControlType::ToolBar,
4344 opt ? opt->state : QStyle::State_None);
4345 if (!resolved.isValid())
4346 break;
4347 const auto &metrics = *resolved.metrics;
4348 const bool horizontal = !opt || (opt->state & State_Horizontal);
4349 const int crossImplicit = horizontal
4350 ? metrics.bgImplicitSize.height()
4351 : metrics.bgImplicitSize.width();
4352 const int crossMargins = horizontal
4353 ? metrics.margins.top() + metrics.margins.bottom()
4354 : metrics.margins.left() + metrics.margins.right();
4355 const int crossPadding = horizontal
4356 ? metrics.padding.top() + metrics.padding.bottom()
4357 : metrics.padding.left() + metrics.padding.right();
4358 return qMax(0, crossImplicit + crossMargins - crossPadding);
4359 }
4360#endif // QT_CONFIG(toolbar)
4361#if QT_CONFIG(tabbar)
4362 case PM_TabBarTabHSpace:
4363 case PM_TabBarTabVSpace:
4364 case PM_TabBarTabOverlap:
4365 // Not supported in StyleKit
4366 case PM_TabCloseIndicatorWidth:
4367 case PM_TabCloseIndicatorHeight:
4368 return 0;
4369#endif // QT_CONFIG(tabbar)
4370 default:
4371 break;
4372 }
4373 return QCommonStyle::pixelMetric(m, opt, widget);
4374}
4375
4376/*! \reimp */
4377int QStyleKitStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
4378 QStyleHintReturn *shret) const
4379{
4380 switch (sh) {
4381 // keep consistent with the Controls style behavior
4382 case SH_SpinBox_SelectOnStep:
4383 case SH_ToolBar_Movable:
4384 case SH_TabBar_PreferNoArrows:
4385 return 0;
4386 case SH_Menu_MouseTracking:
4387 case SH_MenuBar_MouseTracking:
4388 case SH_Menu_Scrollable:
4389 return 1;
4390 default:
4391 break;
4392 }
4393 return QCommonStyle::styleHint(sh, opt, w, shret);
4394}
4395
4396/*! \reimp */
4397QPalette QStyleKitStyle::standardPalette() const
4398{
4399 return QCommonStyle::standardPalette();
4400}
4401
4402/*! \reimp */
4403void QStyleKitStyle::polish(QWidget *widget)
4404{
4405 if (!widget)
4406 return;
4407
4408 Q_D(QStyleKitStyle);
4409
4410 // When no user style is loaded, create the empty fallback style now,
4411 // before any reader is created, so that all widgets are styled consistently
4412 if (!d->style)
4413 d->ensureDefaultStyle();
4414
4415 widget->setAttribute(Qt::WA_Hover);
4416
4417#if QT_CONFIG(scrollbar)
4418 // QScrollBar sets WA_OpaquePaintEvent in its constructor, which skips
4419 // background erase before paint. This can leave artifacts when the
4420 // style's background is invisible, so disable it
4421 if (qobject_cast<QScrollBar *>(widget))
4422 widget->setAttribute(Qt::WA_OpaquePaintEvent, false);
4423#endif
4424
4425 // Create per-widget reader for interactive controls (transitions)
4426 const bool isInteractiveControl = false
4427#if QT_CONFIG(pushbutton)
4428 || qobject_cast<const QPushButton *>(widget)
4429#endif
4430#if QT_CONFIG(checkbox)
4431 || qobject_cast<const QCheckBox *>(widget)
4432#endif
4433#if QT_CONFIG(radiobutton)
4434 || qobject_cast<const QRadioButton *>(widget)
4435#endif
4436#if QT_CONFIG(combobox)
4437 || qobject_cast<const QComboBox *>(widget)
4438 || (widget && widget->inherits("QComboBoxPrivateContainer"))
4439#endif
4440#if QT_CONFIG(lineedit)
4441 || qobject_cast<const QLineEdit *>(widget)
4442#endif
4443#if QT_CONFIG(textedit)
4444 || qobject_cast<const QTextEdit *>(widget)
4445 || qobject_cast<const QPlainTextEdit *>(widget)
4446#endif
4447#if QT_CONFIG(label)
4448 || qobject_cast<const QLabel *>(widget)
4449#endif
4450#if QT_CONFIG(progressbar)
4451 || qobject_cast<const QProgressBar *>(widget)
4452#endif
4453#if QT_CONFIG(slider)
4454 || qobject_cast<const QSlider *>(widget)
4455#endif
4456#if QT_CONFIG(dial)
4457 || qobject_cast<const QDial *>(widget)
4458#endif
4459#if QT_CONFIG(scrollbar)
4460 || qobject_cast<const QScrollBar *>(widget)
4461#endif
4462#if QT_CONFIG(spinbox)
4463 || qobject_cast<const QSpinBox *>(widget)
4464#endif
4465#if QT_CONFIG(tabbar)
4466 || qobject_cast<const QTabBar *>(widget)
4467#endif
4468#if QT_CONFIG(tabwidget)
4469 || qobject_cast<const QTabWidget *>(widget)
4470#endif
4471#if QT_CONFIG(menu)
4472 || qobject_cast<const QMenu *>(widget)
4473 || qobject_cast<const QMenuBar *>(widget)
4474#endif
4475 ;
4476 if (isInteractiveControl)
4477 d->readerForWidget(widget);
4478
4479 d->setStyleAutoFill(widget);
4480 d->setStyleTranslucency(widget);
4481
4482#if QT_CONFIG(lineedit)
4483 if (auto *lineEdit = qobject_cast<QLineEdit *>(widget)) {
4484 if (!lineEdit->property("_q_stylekit_alignment_set").toBool()) {
4485 QQStyleKitReader *r = d->readerForWidget(widget);
4486 if (r) {
4487 const QWidget *target = containerWidget(widget);
4488 QQStyleKitReader::ControlType ct = controlTypeForWidget(target);
4489 r->setControlType(ct);
4490 const auto *textProps = r->global()->text();
4491 if (textProps) {
4492 const uint align = resolvedAlignment(
4493 textProps->alignment(), Qt::AlignLeft, Qt::AlignVCenter);
4494 lineEdit->setAlignment(Qt::Alignment(align));
4495 }
4496 }
4497 }
4498 }
4499#endif
4500
4501 d->refreshStyleFont(widget);
4502 d->refreshStylePalette(widget);
4503 d->refreshStyleMinimumSize(widget);
4504
4505 bool needsEventFilter = isSelfPaintingWidget(widget);
4506#if QT_CONFIG(menu)
4507 // Menus are transient: drop their sub-element tracking when they hide
4508 needsEventFilter = needsEventFilter || qobject_cast<QMenu *>(widget);
4509#endif
4510 if (needsEventFilter)
4511 widget->installEventFilter(this);
4512
4513 QCommonStyle::polish(widget);
4514}
4515
4516/*! \reimp */
4517void QStyleKitStyle::polish(QApplication *app)
4518{
4519 QCommonStyle::polish(app);
4520}
4521
4522/*! \reimp */
4523void QStyleKitStyle::polish(QPalette &palette)
4524{
4525 QCommonStyle::polish(palette);
4526}
4527
4528/*! \reimp */
4529void QStyleKitStyle::unpolish(QWidget *widget)
4530{
4531 Q_D(QStyleKitStyle);
4532 d->unsetStylePalette(widget);
4533 d->unsetStyleFont(widget);
4534 d->unsetStyleMinimumSize(widget);
4535 bool hasEventFilter = isSelfPaintingWidget(widget);
4536#if QT_CONFIG(menu)
4537 hasEventFilter = hasEventFilter || qobject_cast<QMenu *>(widget);
4538#endif
4539 if (hasEventFilter)
4540 widget->removeEventFilter(this);
4541 d->unsetStyleAutoFill(widget);
4542 d->unsetStyleTranslucency(widget);
4543 d->cleanupWidgetReader(widget);
4544#if QT_CONFIG(scrollbar)
4545 if (qobject_cast<QScrollBar *>(widget))
4546 widget->setAttribute(Qt::WA_OpaquePaintEvent);
4547#endif
4548 QCommonStyle::unpolish(widget);
4549}
4550
4551/*! \reimp */
4552void QStyleKitStyle::unpolish(QApplication *app)
4553{
4554 Q_D(QStyleKitStyle);
4555 d->clearMetricsCache();
4556 QCommonStyle::unpolish(app);
4557}
4558
4559/*! \reimp */
4560bool QStyleKitStyle::eventFilter(QObject *obj, QEvent *event)
4561{
4562 Q_D(QStyleKitStyle);
4563 switch (event->type()) {
4564 case QEvent::EnabledChange:
4565 case QEvent::HoverEnter:
4566 case QEvent::HoverLeave:
4567 case QEvent::FocusIn:
4568 case QEvent::FocusOut:
4569 if (auto *w = qobject_cast<QWidget *>(obj)) {
4570 if (d->customPaletteWidgets.contains(w))
4571 d->refreshStylePalette(w);
4572 if (d->customFontWidgets.contains(w))
4573 d->refreshStyleFont(w);
4574 }
4575 break;
4576#if QT_CONFIG(menu)
4577 case QEvent::Hide:
4578 if (auto *menu = qobject_cast<QMenu *>(obj))
4579 d->cleanupSubElements(menu);
4580 break;
4581#endif
4582 default:
4583 break;
4584 }
4585 return QCommonStyle::eventFilter(obj, event);
4586}
4587
4588/*! \reimp */
4589bool QStyleKitStyle::event(QEvent *event)
4590{
4591 return QCommonStyle::event(event);
4592}
4593
4594QT_END_NAMESPACE
4595
4596#include "moc_qstylekitstyle.cpp"
Combined button and popup list for selecting options.
static QWidget * paintTarget(const QWidget *widget)
static bool applyDelegateTransform(QPainter *painter, const QQStyleKitDelegateProperties *element, const QRectF &box)
static void drawStyledItemImage(const QQStyleKitImageProperties *image, const QRectF &rect, qreal opacity, QPainter *painter)
static void drawStyledItemContents(const QQStyleKitDelegateProperties *props, const QRectF &rect, QPainter *painter)
static QWidget * managedViewport(QWidget *widget)
static QMargins elementMargins(const QQStyleKitDelegateProperties *element)
static uint resolvedAlignment(uint raw, Qt::Alignment hDefault, Qt::Alignment vDefault)
static qreal resolvedWidth(const QQStyleKitDelegateProperties *element, qreal availableW)
static bool isSelfPaintingWidget(const QWidget *widget)
static QRect delegateRect(const QQStyleKitDelegateProperties *delegate, const QRect &container, Qt::Alignment hDefault, Qt::Alignment vDefault, const QMargins &padding=QMargins())
static qreal resolvedHeight(const QQStyleKitDelegateProperties *element, qreal availableH)
static QRectF alignedRectInContainer(const QRectF &container, const QSizeF &size, uint alignment, const QMarginsF &padding, const QMarginsF &margins)
static QPixmap iconPixmap(const QIcon &icon, const QSize &size, QStyle::State state, const QPainter *p)
static QUrl urlFromStylePath(const QString &filePath)
static const QWidget * containerWidget(const QWidget *w)
static void drawControlIndicator(const QQStyleKitDelegateProperties *indicator, const QRectF &rect, QPainter *painter)
static void drawControlText(const QQStyleKitTextProperties *textProps, const QFont &font, const QRect &rect, const QString &text, uint textFlags, QPainter *p, Qt::Alignment defaultAlignment=Qt::AlignHCenter|Qt::AlignVCenter)
static void drawStyledItemRect(const QQStyleKitDelegateProperties *props, const QRectF &rect, QPainter *painter)