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
qstylesheetstyle.cpp
Go to the documentation of this file.
1// Copyright (C) 2016 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
4// Qt-Security consideration: Despite of being a data parser, style sheet text is considered trusted input
5
6#include <qglobal.h>
8
9#if QT_CONFIG(style_stylesheet)
10
11#include "private/qcssutil_p.h"
12#include <qdebug.h>
13#include <qdir.h>
14#include <qapplication.h>
15#if QT_CONFIG(menu)
16#include <qmenu.h>
17#endif
18#if QT_CONFIG(menubar)
19#include <qmenubar.h>
20#endif
21#include <qpainter.h>
22#include <qstyleoption.h>
23#if QT_CONFIG(lineedit)
24#include <qlineedit.h>
25#endif
26#if QT_CONFIG(textedit)
27#include <qtextedit.h>
28#include <qplaintextedit.h>
29#endif
30#include <private/qwindowsstyle_p.h>
31#if QT_CONFIG(combobox)
32#include <qcombobox.h>
33#endif
34#include "private/qcssparser_p.h"
35#include "private/qmath_p.h"
36#include <qabstractscrollarea.h>
37#include "private/qabstractscrollarea_p.h"
38#if QT_CONFIG(tooltip)
39#include "private/qtooltip_p.h"
40#endif
41#include <qshareddata.h>
42#if QT_CONFIG(toolbutton)
43#include <qtoolbutton.h>
44#endif
45#if QT_CONFIG(scrollbar)
46#include <qscrollbar.h>
47#endif
48#if QT_CONFIG(abstractslider)
49#include <qabstractslider.h>
50#endif
51#include <qstring.h>
52#include <qfile.h>
53#if QT_CONFIG(checkbox)
54#include <qcheckbox.h>
55#endif
56#if QT_CONFIG(itemviews)
57#include <qheaderview.h>
58#endif
59#include <private/qwindowsstyle_p_p.h>
60#if QT_CONFIG(animation)
61#include <private/qstyleanimation_p.h>
62#endif
63#if QT_CONFIG(tabbar)
64#include <private/qtabbar_p.h>
65#endif
66#include <QMetaProperty>
67#if QT_CONFIG(mainwindow)
68#include <qmainwindow.h>
69#endif
70#if QT_CONFIG(dockwidget)
71#include <qdockwidget.h>
72#endif
73#if QT_CONFIG(mdiarea)
74#include <qmdisubwindow.h>
75#endif
76#if QT_CONFIG(dialog)
77#include <qdialog.h>
78#endif
79#include <private/qwidget_p.h>
80#if QT_CONFIG(spinbox)
81#include <QAbstractSpinBox>
82#endif
83#if QT_CONFIG(label)
84#include <QLabel>
85#endif
86#include "qdrawutil.h"
87#include "qstylehelper_p.h"
88
89#include <limits.h>
90#if QT_CONFIG(toolbar)
91#include <QtWidgets/qtoolbar.h>
92#endif
93#if QT_CONFIG(pushbutton)
94#include <QtWidgets/qpushbutton.h>
95#endif
96
97#include <QtGui/qpainterpath.h>
98#include <QtGui/qpainterstateguard.h>
99#include <QtGui/qscreen.h>
100
101#include <QtCore/private/qduplicatetracker_p.h>
102
103QT_BEGIN_NAMESPACE
104
105using namespace Qt::StringLiterals;
106
107using namespace QCss;
108
109
110class QStyleSheetStylePrivate : public QWindowsStylePrivate
111{
112 Q_DECLARE_PUBLIC(QStyleSheetStyle)
113public:
114 QStyleSheetStylePrivate() { }
115};
116
117class QStyleSheetProxySaver
118{
119public:
120 QStyleSheetProxySaver(const QStyleSheetStyle *that)
121 : m_that(const_cast<QStyleSheetStyle *>(that))
122 , m_oldProxy(const_cast<QStyle *>(that->baseStyle()->proxy()))
123 {
124 m_that->baseStyle()->setProxy(m_that);
125 }
126 ~QStyleSheetProxySaver()
127 {
128 m_that->baseStyle()->setProxy(m_oldProxy);
129 }
130
131private:
132 QStyleSheetStyle *m_that;
133 QStyle *m_oldProxy;
134};
135
136
137static QStyleSheetStyleCaches *styleSheetCaches = nullptr;
138
139/* RECURSION_GUARD:
140 * the QStyleSheetStyle is a proxy. If used with others proxy style, we may end up with something like:
141 * QStyleSheetStyle -> ProxyStyle -> QStyleSheetStyle -> OriginalStyle
142 * Recursion may happen if the style call the widget()->style() again.
143 * Not to mention the performance penalty of having two lookup of rules.
144 *
145 * The first instance of QStyleSheetStyle will set globalStyleSheetStyle to itself. The second one
146 * will notice the globalStyleSheetStyle is not istelf and call its base style directly.
147 */
148static const QStyleSheetStyle *globalStyleSheetStyle = nullptr;
149class QStyleSheetStyleRecursionGuard
150{
151 public:
152 QStyleSheetStyleRecursionGuard(const QStyleSheetStyle *that)
153 : guarded(globalStyleSheetStyle == nullptr)
154 {
155 if (guarded) globalStyleSheetStyle = that;
156 }
157 ~QStyleSheetStyleRecursionGuard() { if (guarded) globalStyleSheetStyle = nullptr; }
158 bool guarded;
159};
160#define RECURSION_GUARD(RETURN)
161 if (globalStyleSheetStyle != 0 && globalStyleSheetStyle != this) { RETURN; }
162 QStyleSheetStyleRecursionGuard recursion_guard(this);
163
164enum PseudoElement {
165 PseudoElement_None,
166 PseudoElement_DownArrow,
167 PseudoElement_UpArrow,
168 PseudoElement_LeftArrow,
169 PseudoElement_RightArrow,
170 PseudoElement_Indicator,
171 PseudoElement_ExclusiveIndicator,
172 PseudoElement_PushButtonMenuIndicator,
173 PseudoElement_ComboBoxDropDown,
174 PseudoElement_ComboBoxArrow,
175 PseudoElement_Item,
176 PseudoElement_SpinBoxUpButton,
177 PseudoElement_SpinBoxUpArrow,
178 PseudoElement_SpinBoxDownButton,
179 PseudoElement_SpinBoxDownArrow,
180 PseudoElement_GroupBoxTitle,
181 PseudoElement_GroupBoxIndicator,
182 PseudoElement_ToolButtonMenu,
183 PseudoElement_ToolButtonMenuArrow,
184 PseudoElement_ToolButtonMenuIndicator,
185 PseudoElement_ToolBoxTab,
186 PseudoElement_ScrollBarSlider,
187 PseudoElement_ScrollBarAddPage,
188 PseudoElement_ScrollBarSubPage,
189 PseudoElement_ScrollBarAddLine,
190 PseudoElement_ScrollBarSubLine,
191 PseudoElement_ScrollBarFirst,
192 PseudoElement_ScrollBarLast,
193 PseudoElement_ScrollBarUpArrow,
194 PseudoElement_ScrollBarDownArrow,
195 PseudoElement_ScrollBarLeftArrow,
196 PseudoElement_ScrollBarRightArrow,
197 PseudoElement_SplitterHandle,
198 PseudoElement_ToolBarHandle,
199 PseudoElement_ToolBarSeparator,
200 PseudoElement_MenuScroller,
201 PseudoElement_MenuTearoff,
202 PseudoElement_MenuCheckMark,
203 PseudoElement_MenuSeparator,
204 PseudoElement_MenuIcon,
205 PseudoElement_MenuRightArrow,
206 PseudoElement_TreeViewBranch,
207 PseudoElement_HeaderViewSection,
208 PseudoElement_HeaderViewUpArrow,
209 PseudoElement_HeaderViewDownArrow,
210 PseudoElement_ProgressBarChunk,
211 PseudoElement_TabBarTab,
212 PseudoElement_TabBarScroller,
213 PseudoElement_TabBarTear,
214 PseudoElement_SliderGroove,
215 PseudoElement_SliderHandle,
216 PseudoElement_SliderAddPage,
217 PseudoElement_SliderSubPage,
218 PseudoElement_SliderTickmark,
219 PseudoElement_TabWidgetPane,
220 PseudoElement_TabWidgetTabBar,
221 PseudoElement_TabWidgetLeftCorner,
222 PseudoElement_TabWidgetRightCorner,
223 PseudoElement_DockWidgetTitle,
224 PseudoElement_DockWidgetCloseButton,
225 PseudoElement_DockWidgetFloatButton,
226 PseudoElement_DockWidgetSeparator,
227 PseudoElement_MdiCloseButton,
228 PseudoElement_MdiMinButton,
229 PseudoElement_MdiNormalButton,
230 PseudoElement_TitleBar,
231 PseudoElement_TitleBarCloseButton,
232 PseudoElement_TitleBarMinButton,
233 PseudoElement_TitleBarMaxButton,
234 PseudoElement_TitleBarShadeButton,
235 PseudoElement_TitleBarUnshadeButton,
236 PseudoElement_TitleBarNormalButton,
237 PseudoElement_TitleBarContextHelpButton,
238 PseudoElement_TitleBarSysMenu,
239 PseudoElement_ViewItem,
240 PseudoElement_ViewItemIcon,
241 PseudoElement_ViewItemText,
242 PseudoElement_ViewItemIndicator,
243 PseudoElement_ScrollAreaCorner,
244 PseudoElement_TabBarTabCloseButton,
245 NumPseudoElements
246};
247
248struct PseudoElementInfo {
249 QStyle::SubControl subControl;
250 const char name[19];
251};
252
253static constexpr PseudoElementInfo knownPseudoElements[NumPseudoElements] = {
254 { QStyle::SC_None, "" },
255 { QStyle::SC_None, "down-arrow" },
256 { QStyle::SC_None, "up-arrow" },
257 { QStyle::SC_None, "left-arrow" },
258 { QStyle::SC_None, "right-arrow" },
259 { QStyle::SC_None, "indicator" },
260 { QStyle::SC_None, "indicator" },
261 { QStyle::SC_None, "menu-indicator" },
262 { QStyle::SC_ComboBoxArrow, "drop-down" },
263 { QStyle::SC_ComboBoxArrow, "down-arrow" },
264 { QStyle::SC_None, "item" },
265 { QStyle::SC_SpinBoxUp, "up-button" },
266 { QStyle::SC_SpinBoxUp, "up-arrow" },
267 { QStyle::SC_SpinBoxDown, "down-button" },
268 { QStyle::SC_SpinBoxDown, "down-arrow" },
269 { QStyle::SC_GroupBoxLabel, "title" },
270 { QStyle::SC_GroupBoxCheckBox, "indicator" },
271 { QStyle::SC_ToolButtonMenu, "menu-button" },
272 { QStyle::SC_ToolButtonMenu, "menu-arrow" },
273 { QStyle::SC_None, "menu-indicator" },
274 { QStyle::SC_None, "tab" },
275 { QStyle::SC_ScrollBarSlider, "handle" },
276 { QStyle::SC_ScrollBarAddPage, "add-page" },
277 { QStyle::SC_ScrollBarSubPage, "sub-page" },
278 { QStyle::SC_ScrollBarAddLine, "add-line" },
279 { QStyle::SC_ScrollBarSubLine, "sub-line" },
280 { QStyle::SC_ScrollBarFirst, "first" },
281 { QStyle::SC_ScrollBarLast, "last" },
282 { QStyle::SC_ScrollBarSubLine, "up-arrow" },
283 { QStyle::SC_ScrollBarAddLine, "down-arrow" },
284 { QStyle::SC_ScrollBarSubLine, "left-arrow" },
285 { QStyle::SC_ScrollBarAddLine, "right-arrow" },
286 { QStyle::SC_None, "handle" },
287 { QStyle::SC_None, "handle" },
288 { QStyle::SC_None, "separator" },
289 { QStyle::SC_None, "scroller" },
290 { QStyle::SC_None, "tearoff" },
291 { QStyle::SC_None, "indicator" },
292 { QStyle::SC_None, "separator" },
293 { QStyle::SC_None, "icon" },
294 { QStyle::SC_None, "right-arrow" },
295 { QStyle::SC_None, "branch" },
296 { QStyle::SC_None, "section" },
297 { QStyle::SC_None, "down-arrow" },
298 { QStyle::SC_None, "up-arrow" },
299 { QStyle::SC_None, "chunk" },
300 { QStyle::SC_None, "tab" },
301 { QStyle::SC_None, "scroller" },
302 { QStyle::SC_None, "tear" },
303 { QStyle::SC_SliderGroove, "groove" },
304 { QStyle::SC_SliderHandle, "handle" },
305 { QStyle::SC_None, "add-page" },
306 { QStyle::SC_None, "sub-page" },
307 { QStyle::SC_SliderTickmarks, "tick-mark" },
308 { QStyle::SC_None, "pane" },
309 { QStyle::SC_None, "tab-bar" },
310 { QStyle::SC_None, "left-corner" },
311 { QStyle::SC_None, "right-corner" },
312 { QStyle::SC_None, "title" },
313 { QStyle::SC_None, "close-button" },
314 { QStyle::SC_None, "float-button" },
315 { QStyle::SC_None, "separator" },
316 { QStyle::SC_MdiCloseButton, "close-button" },
317 { QStyle::SC_MdiMinButton, "minimize-button" },
318 { QStyle::SC_MdiNormalButton, "normal-button" },
319 { QStyle::SC_TitleBarLabel, "title" },
320 { QStyle::SC_TitleBarCloseButton, "close-button" },
321 { QStyle::SC_TitleBarMinButton, "minimize-button" },
322 { QStyle::SC_TitleBarMaxButton, "maximize-button" },
323 { QStyle::SC_TitleBarShadeButton, "shade-button" },
324 { QStyle::SC_TitleBarUnshadeButton, "unshade-button" },
325 { QStyle::SC_TitleBarNormalButton, "normal-button" },
326 { QStyle::SC_TitleBarContextHelpButton, "contexthelp-button" },
327 { QStyle::SC_TitleBarSysMenu, "sys-menu" },
328 { QStyle::SC_None, "item" },
329 { QStyle::SC_None, "icon" },
330 { QStyle::SC_None, "text" },
331 { QStyle::SC_None, "indicator" },
332 { QStyle::SC_None, "corner" },
333 { QStyle::SC_None, "close-button" },
334};
335
336
337struct QStyleSheetBorderImageData : public QSharedData
338{
339 std::array<int, 4> cuts = {-1, -1, -1, -1};
340 QCss::TileMode horizStretch = QCss::TileMode_Unknown;
341 QCss::TileMode vertStretch = QCss::TileMode_Unknown;
342 QPixmap pixmap;
343};
344
345struct QStyleSheetBackgroundData : public QSharedData
346{
347 QStyleSheetBackgroundData(const QBrush& b, const QPixmap& p, QCss::Repeat r,
348 Qt::Alignment a, QCss::Origin o, Attachment t, QCss::Origin c)
349 : brush(b), pixmap(p), repeat(r), position(a), origin(o), attachment(t), clip(c) { }
350
351 bool isTransparent() const {
352 if (brush.style() != Qt::NoBrush)
353 return !brush.isOpaque();
354 return pixmap.isNull() ? false : pixmap.hasAlpha();
355 }
356 QBrush brush;
357 QPixmap pixmap;
358 QCss::Repeat repeat;
359 Qt::Alignment position;
360 QCss::Origin origin;
361 QCss::Attachment attachment;
362 QCss::Origin clip;
363};
364
365struct QStyleSheetBorderData : public QSharedData
366{
367 QStyleSheetBorderData() = default;
368
369 std::array<int, 4> borders = {0, 0, 0, 0};
370 std::array<QBrush, 4> colors;
371 std::array<QCss::BorderStyle, 4> styles = {QCss::BorderStyle_None,
372 QCss::BorderStyle_None,
373 QCss::BorderStyle_None,
374 QCss::BorderStyle_None};
375 std::array<QSize, 4> radii; // topleft, topright, bottomleft, bottomright
376 QSharedDataPointer<QStyleSheetBorderImageData> bi;
377
378 const QStyleSheetBorderImageData *borderImage() const { return bi; }
379 bool hasBorderImage() const { return bi!=nullptr; }
380 bool isOpaque() const
381 {
382 for (size_t i = 0; i < 4; i++) {
383 if (styles[i] == QCss::BorderStyle_Native || styles[i] == QCss::BorderStyle_None)
384 continue;
385 if (styles[i] >= QCss::BorderStyle_Dotted && styles[i] <= QCss::BorderStyle_DotDotDash
386 && styles[i] != BorderStyle_Solid)
387 return false;
388 if (!colors[i].isOpaque())
389 return false;
390 if (!radii[i].isEmpty())
391 return false;
392 }
393 if (bi != nullptr && bi->pixmap.hasAlpha())
394 return false;
395 return true;
396 }
397};
398
399
400struct QStyleSheetOutlineData : public QStyleSheetBorderData
401{
402 QStyleSheetOutlineData() = default;
403
404 std::array<int, 4> offsets = {0, 0, 0, 0};
405};
406
407struct QStyleSheetBoxData : public QSharedData
408{
409 std::array<int, 4> margins = {0, 0, 0, 0};
410 std::array<int, 4> paddings = {0, 0, 0, 0};
411 int spacing = -1;
412};
413
414struct QStyleSheetPaletteData : public QSharedData
415{
416 QStyleSheetPaletteData(const QBrush &foreground,
417 const QBrush &selectedForeground,
418 const QBrush &selectedBackground,
419 const QBrush &alternateBackground,
420 const QBrush &placeHolderTextForeground,
421 const QBrush &accent)
422 : foreground(foreground)
423 , selectionForeground(selectedForeground)
424 , selectionBackground(selectedBackground)
425 , alternateBackground(alternateBackground)
426 , placeholderForeground(placeHolderTextForeground)
427 , accent(accent)
428 { }
429
430 QBrush foreground;
431 QBrush selectionForeground;
432 QBrush selectionBackground;
433 QBrush alternateBackground;
434 QBrush placeholderForeground;
435 QBrush accent;
436};
437
438struct QStyleSheetGeometryData : public QSharedData
439{
440 QStyleSheetGeometryData(int w, int h, int minw, int minh, int maxw, int maxh)
441 : minWidth(minw), minHeight(minh), width(w), height(h), maxWidth(maxw), maxHeight(maxh) { }
442
443 int minWidth, minHeight, width, height, maxWidth, maxHeight;
444};
445
446struct QStyleSheetPositionData : public QSharedData
447{
448 QStyleSheetPositionData(int l, int t, int r, int b, Origin o, Qt::Alignment p, QCss::PositionMode m, Qt::Alignment a = { })
449 : left(l), top(t), bottom(b), right(r), origin(o), position(p), mode(m), textAlignment(a) { }
450
451 int left, top, bottom, right;
452 Origin origin;
453 Qt::Alignment position;
454 QCss::PositionMode mode;
455 Qt::Alignment textAlignment;
456};
457
458struct QStyleSheetImageData : public QSharedData
459{
460 QStyleSheetImageData(const QIcon &i, Qt::Alignment a, const QSize &sz)
461 : icon(i), alignment(a), size(sz) { }
462
463 QIcon icon;
464 Qt::Alignment alignment;
465 QSize size;
466};
467
468class QRenderRule
469{
470public:
471 QRenderRule() : features(0), hasFont(false), pal(nullptr), b(nullptr), bg(nullptr), bd(nullptr), ou(nullptr), geo(nullptr), p(nullptr), img(nullptr), clipset(0) { }
472 QRenderRule(const QList<QCss::Declaration> &, const QObject *);
473
474 QRect borderRect(const QRect &r) const;
475 QRect outlineRect(const QRect &r) const;
476 QRect paddingRect(const QRect &r) const;
477 QRect contentsRect(const QRect &r) const;
478
479 enum { Margin = 1, Border = 2, Padding = 4, All=Margin|Border|Padding };
480 QRect boxRect(const QRect &r, int flags = All) const;
481 QSize boxSize(const QSize &s, int flags = All) const;
482 QRect originRect(const QRect &rect, Origin origin) const;
483
484 QPainterPath borderClip(QRect rect);
485 void drawBorder(QPainter *, const QRect&);
486 void drawOutline(QPainter *, const QRect&);
487 void drawBorderImage(QPainter *, const QRect&);
488 void drawBackground(QPainter *, const QRect&, const QPoint& = QPoint(0, 0));
489 void drawBackgroundImage(QPainter *, const QRect&, QPoint = QPoint(0, 0));
490 void drawFrame(QPainter *, const QRect&);
491 void drawImage(QPainter *p, const QRect &rect);
492 void drawRule(QPainter *, const QRect&);
493 void configurePalette(QPalette *, QPalette::ColorGroup, const QWidget *, bool);
494 void configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette::ColorRole br);
495
496 const QStyleSheetPaletteData *palette() const { return pal; }
497 const QStyleSheetBoxData *box() const { return b; }
498 const QStyleSheetBackgroundData *background() const { return bg; }
499 const QStyleSheetBorderData *border() const { return bd; }
500 const QStyleSheetOutlineData *outline() const { return ou; }
501 const QStyleSheetGeometryData *geometry() const { return geo; }
502 const QStyleSheetPositionData *position() const { return p; }
503 const QStyleSheetImageData *icon() const { return iconPtr; }
504
505 bool hasModification() const;
506
507 bool hasPalette() const { return pal != nullptr; }
508 bool hasBackground() const { return bg != nullptr && (!bg->pixmap.isNull() || bg->brush.style() != Qt::NoBrush); }
509 bool hasGradientBackground() const { return bg && bg->brush.style() >= Qt::LinearGradientPattern
510 && bg->brush.style() <= Qt::ConicalGradientPattern; }
511
512 bool hasNativeBorder() const {
513 return bd == nullptr
514 || (!bd->hasBorderImage() && bd->styles[0] == BorderStyle_Native);
515 }
516
517 bool hasNativeOutline() const {
518 return (ou == nullptr
519 || (!ou->hasBorderImage() && ou->styles[0] == BorderStyle_Native));
520 }
521
522 bool baseStyleCanDraw() const {
523 if (!hasBackground() || (background()->brush.style() == Qt::NoBrush && bg->pixmap.isNull()))
524 return true;
525 if (bg && !bg->pixmap.isNull())
526 return false;
527 if (hasGradientBackground())
528 return features & StyleFeature_BackgroundGradient;
529 return features & StyleFeature_BackgroundColor;
530 }
531
532 bool hasBox() const { return b != nullptr; }
533 bool hasBorder() const { return bd != nullptr; }
534 bool hasOutline() const { return ou != nullptr; }
535 bool hasPosition() const { return p != nullptr; }
536 bool hasGeometry() const { return geo != nullptr; }
537 bool hasDrawable() const { return !hasNativeBorder() || hasBackground() || hasImage(); }
538 bool hasImage() const { return img != nullptr; }
539 bool hasIcon() const { return iconPtr != nullptr; }
540
541 QSize minimumContentsSize() const
542 { return geo ? QSize(geo->minWidth, geo->minHeight) : QSize(0, 0); }
543 QSize minimumSize() const
544 { return boxSize(minimumContentsSize()); }
545
546 QSize contentsSize() const
547 { return geo ? QSize(geo->width, geo->height)
548 : ((img && img->size.isValid()) ? img->size : QSize()); }
549 QSize contentsSize(const QSize &sz) const
550 {
551 QSize csz = contentsSize();
552 if (csz.width() == -1) csz.setWidth(sz.width());
553 if (csz.height() == -1) csz.setHeight(sz.height());
554 return csz;
555 }
556 bool hasContentsSize() const
557 { return (geo && (geo->width != -1 || geo->height != -1)) || (img && img->size.isValid()); }
558
559 QSize size() const { return boxSize(contentsSize()); }
560 QSize size(const QSize &sz) const { return boxSize(contentsSize(sz)); }
561 QSize adjustSize(const QSize &sz)
562 {
563 if (!geo)
564 return sz;
565 QSize csz = contentsSize();
566 if (csz.width() == -1) csz.setWidth(sz.width());
567 if (csz.height() == -1) csz.setHeight(sz.height());
568 if (geo->maxWidth != -1 && csz.width() > geo->maxWidth) csz.setWidth(geo->maxWidth);
569 if (geo->maxHeight != -1 && csz.height() > geo->maxHeight) csz.setHeight(geo->maxHeight);
570 csz=csz.expandedTo(QSize(geo->minWidth, geo->minHeight));
571 return csz;
572 }
573
574 QVariant styleHint(QLatin1StringView sh) const { return styleHints.value(sh); }
575
576 void fixupBorder(int);
577
578 // Shouldn't be here
579 void setClip(QPainter *p, const QRect &rect);
580 void unsetClip(QPainter *);
581
582public:
583 int features;
584 QBrush defaultBackground;
585 QFont font; // Be careful using this font directly. Prefer using font.resolve( )
586 bool hasFont;
587
588 QHash<QString, QVariant> styleHints;
589
590 QSharedDataPointer<QStyleSheetPaletteData> pal;
591 QSharedDataPointer<QStyleSheetBoxData> b;
592 QSharedDataPointer<QStyleSheetBackgroundData> bg;
593 QSharedDataPointer<QStyleSheetBorderData> bd;
594 QSharedDataPointer<QStyleSheetOutlineData> ou;
595 QSharedDataPointer<QStyleSheetGeometryData> geo;
596 QSharedDataPointer<QStyleSheetPositionData> p;
597 QSharedDataPointer<QStyleSheetImageData> img;
598 QSharedDataPointer<QStyleSheetImageData> iconPtr;
599
600 int clipset;
601 QPainterPath clipPath;
602};
603Q_DECLARE_TYPEINFO(QRenderRule, Q_RELOCATABLE_TYPE);
604
605///////////////////////////////////////////////////////////////////////////////////////////
606static constexpr std::array<const char*, 90> knownStyleHints = {
607 "activate-on-singleclick",
608 "alignment",
609 "arrow-keys-navigate-into-children",
610 "backward-icon",
611 "button-layout",
612 "cd-icon",
613 "combobox-list-mousetracking",
614 "combobox-popup",
615 "computer-icon",
616 "desktop-icon",
617 "dialog-apply-icon",
618 "dialog-cancel-icon",
619 "dialog-close-icon",
620 "dialog-discard-icon",
621 "dialog-help-icon",
622 "dialog-no-icon",
623 "dialog-ok-icon",
624 "dialog-open-icon",
625 "dialog-reset-icon",
626 "dialog-save-icon",
627 "dialog-yes-icon",
628 "dialogbuttonbox-buttons-have-icons",
629 "directory-closed-icon",
630 "directory-icon",
631 "directory-link-icon",
632 "directory-open-icon",
633 "dither-disable-text",
634 "dockwidget-close-icon",
635 "downarrow-icon",
636 "dvd-icon",
637 "etch-disabled-text",
638 "file-icon",
639 "file-link-icon",
640 "filedialog-backward-icon", // unused
641 "filedialog-contentsview-icon",
642 "filedialog-detailedview-icon",
643 "filedialog-end-icon",
644 "filedialog-infoview-icon",
645 "filedialog-listview-icon",
646 "filedialog-new-directory-icon",
647 "filedialog-parent-directory-icon",
648 "filedialog-start-icon",
649 "floppy-icon",
650 "forward-icon",
651 "gridline-color",
652 "harddisk-icon",
653 "home-icon",
654 "lineedit-clear-button-icon",
655 "icon-size",
656 "leftarrow-icon",
657 "lineedit-password-character",
658 "lineedit-password-mask-delay",
659 "mdi-fill-space-on-maximize",
660 "menu-scrollable",
661 "menubar-altkey-navigation",
662 "menubar-separator",
663 "messagebox-critical-icon",
664 "messagebox-information-icon",
665 "messagebox-question-icon",
666 "messagebox-text-interaction-flags",
667 "messagebox-warning-icon",
668 "mouse-tracking",
669 "network-icon",
670 "opacity",
671 "paint-alternating-row-colors-for-empty-area",
672 "rightarrow-icon",
673 "scrollbar-contextmenu",
674 "scrollbar-leftclick-absolute-position",
675 "scrollbar-middleclick-absolute-position",
676 "scrollbar-roll-between-buttons",
677 "scrollbar-scroll-when-pointer-leaves-control",
678 "scrollview-frame-around-contents",
679 "show-decoration-selected",
680 "spinbox-click-autorepeat-rate",
681 "spincontrol-disable-on-bounds",
682 "tabbar-elide-mode",
683 "tabbar-prefer-no-arrows",
684 "titlebar-close-icon",
685 "titlebar-contexthelp-icon",
686 "titlebar-maximize-icon",
687 "titlebar-menu-icon",
688 "titlebar-minimize-icon",
689 "titlebar-normal-icon",
690 "titlebar-shade-icon",
691 "titlebar-show-tooltips-on-buttons",
692 "titlebar-unshade-icon",
693 "toolbutton-popup-delay",
694 "trash-icon",
695 "uparrow-icon",
696 "widget-animation-duration"
697};
698
699static QList<QVariant> subControlLayout(QByteArrayView layout)
700{
701 QList<QVariant> buttons;
702 for (int button : layout) {
703 switch (button) {
704 case 'm':
705 buttons.append(PseudoElement_MdiMinButton);
706 buttons.append(PseudoElement_TitleBarMinButton);
707 break;
708 case 'M':
709 buttons.append(PseudoElement_TitleBarMaxButton);
710 break;
711 case 'X':
712 buttons.append(PseudoElement_MdiCloseButton);
713 buttons.append(PseudoElement_TitleBarCloseButton);
714 break;
715 case 'N':
716 buttons.append(PseudoElement_MdiNormalButton);
717 buttons.append(PseudoElement_TitleBarNormalButton);
718 break;
719 case 'I':
720 buttons.append(PseudoElement_TitleBarSysMenu);
721 break;
722 case 'T':
723 buttons.append(PseudoElement_TitleBar);
724 break;
725 case 'H':
726 buttons.append(PseudoElement_TitleBarContextHelpButton);
727 break;
728 case 'S':
729 buttons.append(PseudoElement_TitleBarShadeButton);
730 break;
731 default:
732 buttons.append(button);
733 break;
734 }
735 }
736 return buttons;
737}
738
739namespace {
740 struct ButtonInfo {
741 QRenderRule rule;
742 int element;
743 int offset;
744 int where;
745 int width;
746 };
747}
748template <> class QTypeInfo<ButtonInfo> : public QTypeInfoMerger<ButtonInfo, QRenderRule, int> {};
749
750QHash<QStyle::SubControl, QRect> QStyleSheetStyle::titleBarLayout(const QWidget *w, const QStyleOptionTitleBar *tb) const
751{
752 QHash<QStyle::SubControl, QRect> layoutRects;
753 const bool isMinimized = tb->titleBarState & Qt::WindowMinimized;
754 const bool isMaximized = tb->titleBarState & Qt::WindowMaximized;
755 QRenderRule subRule = renderRule(w, tb);
756 QRect cr = subRule.contentsRect(tb->rect);
757 QList<QVariant> layout = subRule.styleHint("button-layout"_L1).toList();
758 if (layout.isEmpty())
759 layout = subControlLayout("I(T)HSmMX"_L1);
760
761 int offsets[3] = { 0, 0, 0 };
762 enum Where { Left, Right, Center, NoWhere } where = Left;
763 QList<ButtonInfo> infos;
764 infos.reserve(layout.size());
765 for (const QVariant &val : std::as_const(layout)) {
766 const int element = val.toInt();
767 if (element == '(') {
768 where = Center;
769 } else if (element == ')') {
770 where = Right;
771 } else {
772 ButtonInfo info;
773 info.element = element;
774 switch (element) {
775 case PseudoElement_TitleBar:
776 if (!(tb->titleBarFlags & (Qt::WindowTitleHint | Qt::WindowSystemMenuHint)))
777 continue;
778 break;
779 case PseudoElement_TitleBarContextHelpButton:
780 if (!(tb->titleBarFlags & Qt::WindowContextHelpButtonHint))
781 continue;
782 break;
783 case PseudoElement_TitleBarMinButton:
784 if (!(tb->titleBarFlags & Qt::WindowMinimizeButtonHint))
785 continue;
786 if (isMinimized)
787 info.element = PseudoElement_TitleBarNormalButton;
788 break;
789 case PseudoElement_TitleBarMaxButton:
790 if (!(tb->titleBarFlags & Qt::WindowMaximizeButtonHint))
791 continue;
792 if (isMaximized)
793 info.element = PseudoElement_TitleBarNormalButton;
794 break;
795 case PseudoElement_TitleBarShadeButton:
796 if (!(tb->titleBarFlags & Qt::WindowShadeButtonHint))
797 continue;
798 if (isMinimized)
799 info.element = PseudoElement_TitleBarUnshadeButton;
800 break;
801 case PseudoElement_TitleBarCloseButton:
802 case PseudoElement_TitleBarSysMenu:
803 if (!(tb->titleBarFlags & Qt::WindowSystemMenuHint))
804 continue;
805 break;
806 default:
807 continue;
808 }
809 if (info.element == PseudoElement_TitleBar) {
810 info.width = tb->fontMetrics.horizontalAdvance(tb->text) + 6;
811 subRule.geo = new QStyleSheetGeometryData(info.width, tb->fontMetrics.height(), -1, -1, -1, -1);
812 } else {
813 subRule = renderRule(w, tb, info.element);
814 info.width = subRule.size().width();
815 }
816 info.rule = subRule;
817 info.offset = offsets[where];
818 info.where = where;
819 offsets[where] += info.width;
820
821 infos.append(std::move(info));
822 }
823 }
824
825 for (const ButtonInfo &info : std::as_const(infos)) {
826 QRect lr = cr;
827 switch (info.where) {
828 case Center: {
829 lr.setLeft(cr.left() + offsets[Left]);
830 lr.setRight(cr.right() - offsets[Right]);
831 QRect r(0, 0, offsets[Center], lr.height());
832 r.moveCenter(lr.center());
833 r.setLeft(r.left()+info.offset);
834 r.setWidth(info.width);
835 lr = r;
836 break; }
837 case Left:
838 lr.translate(info.offset, 0);
839 lr.setWidth(info.width);
840 break;
841 case Right:
842 lr.moveLeft(cr.right() + 1 - offsets[Right] + info.offset);
843 lr.setWidth(info.width);
844 break;
845 default:
846 break;
847 }
848 QStyle::SubControl control = knownPseudoElements[info.element].subControl;
849 layoutRects[control] = positionRect(w, info.rule, info.element, lr, tb->direction);
850 }
851
852 return layoutRects;
853}
854
855static QStyle::StandardPixmap subControlIcon(int pe)
856{
857 switch (pe) {
858 case PseudoElement_MdiCloseButton: return QStyle::SP_TitleBarCloseButton;
859 case PseudoElement_MdiMinButton: return QStyle::SP_TitleBarMinButton;
860 case PseudoElement_MdiNormalButton: return QStyle::SP_TitleBarNormalButton;
861 case PseudoElement_TitleBarCloseButton: return QStyle::SP_TitleBarCloseButton;
862 case PseudoElement_TitleBarMinButton: return QStyle::SP_TitleBarMinButton;
863 case PseudoElement_TitleBarMaxButton: return QStyle::SP_TitleBarMaxButton;
864 case PseudoElement_TitleBarShadeButton: return QStyle::SP_TitleBarShadeButton;
865 case PseudoElement_TitleBarUnshadeButton: return QStyle::SP_TitleBarUnshadeButton;
866 case PseudoElement_TitleBarNormalButton: return QStyle::SP_TitleBarNormalButton;
867 case PseudoElement_TitleBarContextHelpButton: return QStyle::SP_TitleBarContextHelpButton;
868 default: break;
869 }
870 return QStyle::SP_CustomBase;
871}
872
873QRenderRule::QRenderRule(const QList<Declaration> &declarations, const QObject *object)
874 : features(0),
875 hasFont(false),
876 pal(nullptr),
877 b(nullptr),
878 bg(nullptr),
879 bd(nullptr),
880 ou(nullptr),
881 geo(nullptr),
882 p(nullptr),
883 img(nullptr),
884 clipset(0)
885{
886 QPalette palette = QGuiApplication::palette(); // ###: ideally widget's palette
887 ValueExtractor v(declarations, palette);
888 features = v.extractStyleFeatures();
889
890 int w = -1, h = -1, minw = -1, minh = -1, maxw = -1, maxh = -1;
891 if (v.extractGeometry(&w, &h, &minw, &minh, &maxw, &maxh))
892 geo = new QStyleSheetGeometryData(w, h, minw, minh, maxw, maxh);
893
894 int left = 0, top = 0, right = 0, bottom = 0;
895 Origin origin = Origin_Unknown;
896 Qt::Alignment position;
897 QCss::PositionMode mode = PositionMode_Unknown;
898 Qt::Alignment textAlignment;
899 if (v.extractPosition(&left, &top, &right, &bottom, &origin, &position, &mode, &textAlignment))
900 p = new QStyleSheetPositionData(left, top, right, bottom, origin, position, mode, textAlignment);
901
902 b = new QStyleSheetBoxData;
903 if (!v.extractBox(b->margins.data(), b->paddings.data(), &b->spacing))
904 b = nullptr;
905
906 bd = new QStyleSheetBorderData;
907 if (!v.extractBorder(bd->borders.data(), bd->colors.data(), bd->styles.data(), bd->radii.data()))
908 bd = nullptr;
909
910 ou = new QStyleSheetOutlineData;
911 if (!v.extractOutline(ou->borders.data(), ou->colors.data(), ou->styles.data(), ou->radii.data(), ou->offsets.data()))
912 ou = nullptr;
913
914 QBrush brush;
915 QString uri;
916 Repeat repeat = Repeat_XY;
917 Qt::Alignment alignment = Qt::AlignTop | Qt::AlignLeft;
918 Attachment attachment = Attachment_Scroll;
919 origin = Origin_Padding;
920 Origin clip = Origin_Border;
921 if (v.extractBackground(&brush, &uri, &repeat, &alignment, &origin, &attachment, &clip)) {
922 QPixmap pixmap = QStyleSheetStyle::loadPixmap(uri, object);
923 if (!uri.isEmpty() && pixmap.isNull())
924 qWarning("Could not create pixmap from %s", qPrintable(QDir::toNativeSeparators(uri)));
925 bg = new QStyleSheetBackgroundData(brush, pixmap, repeat, alignment, origin, attachment, clip);
926 }
927
928 QBrush foreground;
929 QBrush selectedForeground;
930 QBrush selectedBackground;
931 QBrush alternateBackground;
932 QBrush placeHolderTextForeground;
933 QBrush accent;
934 if (v.extractPalette(&foreground, &selectedForeground, &selectedBackground,
935 &alternateBackground, &placeHolderTextForeground, &accent)) {
936 pal = new QStyleSheetPaletteData(foreground, selectedForeground, selectedBackground,
937 alternateBackground, placeHolderTextForeground, accent);
938 }
939
940 QIcon imgIcon;
941 alignment = Qt::AlignCenter;
942 QSize imgSize;
943 if (v.extractImage(&imgIcon, &alignment, &imgSize))
944 img = new QStyleSheetImageData(imgIcon, alignment, imgSize);
945
946 QIcon icon;
947 QSize size;
948 if (v.extractIcon(&icon, &size))
949 iconPtr = new QStyleSheetImageData(icon, Qt::AlignCenter, size);
950
951 int adj = -255;
952 hasFont = v.extractFont(&font, &adj);
953
954#if QT_CONFIG(tooltip)
955 if (qobject_cast<const QTipLabel *>(object) != nullptr)
956 palette = QToolTip::palette();
957#endif
958
959 for (const Declaration &decl : declarations) {
960 if (decl.d->propertyId == BorderImage) {
961 QString uri;
962 QCss::TileMode horizStretch, vertStretch;
963 std::array<int, 4> cuts;
964
965 decl.borderImageValue(&uri, cuts.data(), &horizStretch, &vertStretch);
966 if (uri.isEmpty() || uri == "none"_L1) {
967 if (bd && bd->bi)
968 bd->bi->pixmap = QPixmap();
969 } else {
970 if (!bd)
971 bd = new QStyleSheetBorderData;
972 if (!bd->bi)
973 bd->bi = new QStyleSheetBorderImageData;
974
975 QStyleSheetBorderImageData *bi = bd->bi;
976 bi->pixmap = QStyleSheetStyle::loadPixmap(uri, object);
977 bi->cuts = cuts;
978 bi->horizStretch = horizStretch;
979 bi->vertStretch = vertStretch;
980 }
981 } else if (decl.d->propertyId == QtBackgroundRole) {
982 if (bg && bg->brush.style() != Qt::NoBrush)
983 continue;
984 int role = decl.d->values.at(0).variant.toInt();
985 if (role >= Value_FirstColorRole && role <= Value_LastColorRole)
986 defaultBackground = palette.color((QPalette::ColorRole)(role-Value_FirstColorRole));
987 } else if (decl.d->property.startsWith("qproperty-"_L1, Qt::CaseInsensitive)) {
988 // intentionally left blank...
989 } else if (decl.d->propertyId == UnknownProperty) {
990 bool knownStyleHint = false;
991 for (const auto sh : knownStyleHints) {
992 QLatin1StringView styleHint(sh);
993 if (decl.d->property == styleHint) {
994 QVariant hintValue;
995 if (styleHint.endsWith("alignment"_L1)) {
996 hintValue = (int) decl.alignmentValue();
997 } else if (styleHint.endsWith("color"_L1)) {
998 hintValue = (int) decl.colorValue().rgba();
999 } else if (styleHint.endsWith("size"_L1)) {
1000 // Check only for the 'em' case
1001 const QString valueString = decl.d->values.at(0).variant.toString();
1002 const bool isEmSize = valueString.endsWith(u"em", Qt::CaseInsensitive);
1003 if (isEmSize || valueString.endsWith(u"ex", Qt::CaseInsensitive)) {
1004 // 1em == size of font; 1ex == xHeight of font
1005 // See lengthValueFromData helper in qcssparser.cpp
1006 QFont fontForSize(font);
1007 // if no font is specified, then use the widget font if possible
1008 if (const QWidget *widget; !hasFont && (widget = qobject_cast<const QWidget*>(object)))
1009 fontForSize = widget->font();
1010
1011 const QFontMetrics fontMetrics(fontForSize);
1012 qreal pixelSize = isEmSize ? fontMetrics.height() : fontMetrics.xHeight();
1013
1014 // Transform size according to the 'em'/'ex' value
1015 qreal emexSize = {};
1016 if (decl.realValue(&emexSize, isEmSize ? "em" : "ex") && emexSize > 0) {
1017 pixelSize *= emexSize;
1018 const QSizeF newSize(pixelSize, pixelSize);
1019 decl.d->parsed = QVariant::fromValue<QSizeF>(newSize);
1020 hintValue = newSize;
1021 } else {
1022 qWarning("Invalid '%s' size for %s. Skipping.",
1023 isEmSize ? "em" : "ex", qPrintable(valueString));
1024 }
1025 } else {
1026 // Normal case where we receive a 'px' or 'pt' unit
1027 hintValue = decl.sizeValue();
1028 }
1029 } else if (styleHint.endsWith("icon"_L1)) {
1030 hintValue = decl.iconValue();
1031 } else if (styleHint == "button-layout"_L1 && decl.d->values.size() != 0
1032 && decl.d->values.at(0).type == QCss::Value::String) {
1033 hintValue = subControlLayout(decl.d->values.at(0).variant.toString().toLatin1());
1034 } else {
1035 int integer;
1036 decl.intValue(&integer);
1037 hintValue = integer;
1038 }
1039 styleHints[decl.d->property] = hintValue;
1040 knownStyleHint = true;
1041 break;
1042 }
1043 }
1044 if (!knownStyleHint)
1045 qWarning("Unknown property %s", qPrintable(decl.d->property));
1046 }
1047 }
1048
1049 if (hasBorder()) {
1050 if (const QWidget *widget = qobject_cast<const QWidget *>(object)) {
1051 QStyleSheetStyle *style = const_cast<QStyleSheetStyle *>(globalStyleSheetStyle);
1052 if (!style)
1053 style = qt_styleSheet(widget->style());
1054 if (style)
1055 fixupBorder(style->nativeFrameWidth(widget));
1056 }
1057 if (border()->hasBorderImage())
1058 defaultBackground = QBrush();
1059 }
1060}
1061
1062QRect QRenderRule::borderRect(const QRect& r) const
1063{
1064 if (!hasBox())
1065 return r;
1066 const auto &m = box()->margins;
1067 return r.adjusted(m[LeftEdge], m[TopEdge], -m[RightEdge], -m[BottomEdge]);
1068}
1069
1070QRect QRenderRule::outlineRect(const QRect& r) const
1071{
1072 QRect br = borderRect(r);
1073 if (!hasOutline())
1074 return br;
1075 const auto &b = outline()->borders;
1076 return r.adjusted(b[LeftEdge], b[TopEdge], -b[RightEdge], -b[BottomEdge]);
1077}
1078
1079QRect QRenderRule::paddingRect(const QRect& r) const
1080{
1081 QRect br = borderRect(r);
1082 if (!hasBorder())
1083 return br;
1084 const auto &b = border()->borders;
1085 return br.adjusted(b[LeftEdge], b[TopEdge], -b[RightEdge], -b[BottomEdge]);
1086}
1087
1088QRect QRenderRule::contentsRect(const QRect& r) const
1089{
1090 QRect pr = paddingRect(r);
1091 if (!hasBox())
1092 return pr;
1093 const auto &p = box()->paddings;
1094 return pr.adjusted(p[LeftEdge], p[TopEdge], -p[RightEdge], -p[BottomEdge]);
1095}
1096
1097QRect QRenderRule::boxRect(const QRect& cr, int flags) const
1098{
1099 QRect r = cr;
1100 if (hasBox()) {
1101 if (flags & Margin) {
1102 const auto &m = box()->margins;
1103 r.adjust(-m[LeftEdge], -m[TopEdge], m[RightEdge], m[BottomEdge]);
1104 }
1105 if (flags & Padding) {
1106 const auto &p = box()->paddings;
1107 r.adjust(-p[LeftEdge], -p[TopEdge], p[RightEdge], p[BottomEdge]);
1108 }
1109 }
1110 if (hasBorder() && (flags & Border)) {
1111 const auto &b = border()->borders;
1112 r.adjust(-b[LeftEdge], -b[TopEdge], b[RightEdge], b[BottomEdge]);
1113 }
1114 return r;
1115}
1116
1117QSize QRenderRule::boxSize(const QSize &cs, int flags) const
1118{
1119 QSize bs = boxRect(QRect(QPoint(0, 0), cs), flags).size();
1120 if (cs.width() < 0) bs.setWidth(-1);
1121 if (cs.height() < 0) bs.setHeight(-1);
1122 return bs;
1123}
1124
1125void QRenderRule::fixupBorder(int nativeWidth)
1126{
1127 if (bd == nullptr)
1128 return;
1129
1130 if (!bd->hasBorderImage() || bd->bi->pixmap.isNull()) {
1131 bd->bi = nullptr;
1132 // ignore the color, border of edges that have none border-style
1133 QBrush color = pal ? pal->foreground : QBrush();
1134 const bool hasRadius = bd->radii[0].isValid() || bd->radii[1].isValid()
1135 || bd->radii[2].isValid() || bd->radii[3].isValid();
1136 for (int i = 0; i < 4; i++) {
1137 if ((bd->styles[i] == BorderStyle_Native) && hasRadius)
1138 bd->styles[i] = BorderStyle_None;
1139
1140 switch (bd->styles[i]) {
1141 case BorderStyle_None:
1142 // border-style: none forces width to be 0
1143 bd->colors[i] = QBrush();
1144 bd->borders[i] = 0;
1145 break;
1146 case BorderStyle_Native:
1147 if (bd->borders[i] == 0)
1148 bd->borders[i] = nativeWidth;
1149 Q_FALLTHROUGH();
1150 default:
1151 if (bd->colors[i].style() == Qt::NoBrush) // auto-acquire 'color'
1152 bd->colors[i] = color;
1153 break;
1154 }
1155 }
1156
1157 return;
1158 }
1159
1160 // inspect the border image
1161 QStyleSheetBorderImageData *bi = bd->bi;
1162 if (bi->cuts[0] == -1) {
1163 for (int i = 0; i < 4; i++) // assume, cut = border
1164 bi->cuts[i] = int(border()->borders[i]);
1165 }
1166}
1167
1168void QRenderRule::drawBorderImage(QPainter *p, const QRect& rect)
1169{
1170 setClip(p, rect);
1171 const auto tileMode2TileRule = [](TileMode tileMode) -> Qt::TileRule {
1172 switch (tileMode) {
1173 case TileMode_Unknown:
1174 case TileMode_Stretch:
1175 return Qt::StretchTile;
1176 case TileMode_Round:
1177 return Qt::RoundTile;
1178 case TileMode_Repeat:
1179 return Qt::RepeatTile;
1180 }
1181 qWarning() << "Invalid tile mode:" << tileMode;
1182 Q_UNREACHABLE_RETURN(Qt::StretchTile);
1183 };
1184
1185 const QStyleSheetBorderImageData *borderImageData = border()->borderImage();
1186 const auto &targetBorders = border()->borders;
1187 const auto sourceBorders = borderImageData->cuts;
1188 QMargins sourceMargins(sourceBorders[LeftEdge], sourceBorders[TopEdge],
1189 sourceBorders[RightEdge], sourceBorders[BottomEdge]);
1190 QMargins targetMargins(targetBorders[LeftEdge], targetBorders[TopEdge],
1191 targetBorders[RightEdge], targetBorders[BottomEdge]);
1192
1193 bool wasSmoothPixmapTransform = p->renderHints() & QPainter::SmoothPixmapTransform;
1194 p->setRenderHint(QPainter::SmoothPixmapTransform);
1195 qDrawBorderPixmap(p, rect, targetMargins, borderImageData->pixmap,
1196 QRect(QPoint(), borderImageData->pixmap.size()), sourceMargins,
1197 QTileRules(tileMode2TileRule(borderImageData->horizStretch),
1198 tileMode2TileRule(borderImageData->vertStretch)));
1199 p->setRenderHint(QPainter::SmoothPixmapTransform, wasSmoothPixmapTransform);
1200 unsetClip(p);
1201}
1202
1203QRect QRenderRule::originRect(const QRect &rect, Origin origin) const
1204{
1205 switch (origin) {
1206 case Origin_Padding:
1207 return paddingRect(rect);
1208 case Origin_Border:
1209 return borderRect(rect);
1210 case Origin_Content:
1211 return contentsRect(rect);
1212 case Origin_Margin:
1213 default:
1214 return rect;
1215 }
1216}
1217
1218void QRenderRule::drawBackgroundImage(QPainter *p, const QRect &rect, QPoint off)
1219{
1220 if (!hasBackground())
1221 return;
1222
1223 const QPixmap& bgp = background()->pixmap;
1224 if (bgp.isNull())
1225 return;
1226
1227 setClip(p, borderRect(rect));
1228
1229 if (background()->origin != background()->clip) {
1230 p->save();
1231 p->setClipRect(originRect(rect, background()->clip), Qt::IntersectClip);
1232 }
1233
1234 if (background()->attachment == Attachment_Fixed)
1235 off = QPoint(0, 0);
1236
1237 QSize bgpSize = bgp.size() / bgp.devicePixelRatio();
1238 int bgpHeight = bgpSize.height();
1239 int bgpWidth = bgpSize.width();
1240 QRect r = originRect(rect, background()->origin);
1241 QRect aligned = QStyle::alignedRect(Qt::LeftToRight, background()->position, bgpSize, r);
1242 QRect inter = aligned.translated(-off).intersected(r);
1243
1244 switch (background()->repeat) {
1245 case Repeat_Y:
1246 p->drawTiledPixmap(inter.x(), r.y(), inter.width(), r.height(), bgp,
1247 inter.x() - aligned.x() + off.x(),
1248 bgpHeight - int(aligned.y() - r.y()) % bgpHeight + off.y());
1249 break;
1250 case Repeat_X:
1251 p->drawTiledPixmap(r.x(), inter.y(), r.width(), inter.height(), bgp,
1252 bgpWidth - int(aligned.x() - r.x())%bgpWidth + off.x(),
1253 inter.y() - aligned.y() + off.y());
1254 break;
1255 case Repeat_XY:
1256 p->drawTiledPixmap(r, bgp,
1257 QPoint(bgpWidth - int(aligned.x() - r.x())% bgpWidth + off.x(),
1258 bgpHeight - int(aligned.y() - r.y())%bgpHeight + off.y()));
1259 break;
1260 case Repeat_None:
1261 default:
1262 p->drawPixmap(inter.x(), inter.y(), bgp, inter.x() - aligned.x() + off.x(),
1263 inter.y() - aligned.y() + off.y(), bgp.width() , bgp.height());
1264 break;
1265 }
1266
1267
1268 if (background()->origin != background()->clip)
1269 p->restore();
1270
1271 unsetClip(p);
1272}
1273
1274void QRenderRule::drawOutline(QPainter *p, const QRect &rect)
1275{
1276 if (!hasOutline())
1277 return;
1278
1279 bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
1280 p->setRenderHint(QPainter::Antialiasing);
1281 qDrawBorder(p, rect, ou->styles.data(), ou->borders.data(), ou->colors.data(), ou->radii.data());
1282 p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
1283}
1284
1285void QRenderRule::drawBorder(QPainter *p, const QRect& rect)
1286{
1287 if (!hasBorder())
1288 return;
1289
1290 if (border()->hasBorderImage()) {
1291 drawBorderImage(p, rect);
1292 return;
1293 }
1294
1295 bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
1296 p->setRenderHint(QPainter::Antialiasing);
1297 qDrawBorder(p, rect, bd->styles.data(), bd->borders.data(), bd->colors.data(), bd->radii.data());
1298 p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
1299}
1300
1301QPainterPath QRenderRule::borderClip(QRect r)
1302{
1303 if (!hasBorder())
1304 return QPainterPath();
1305
1306 QSize tlr, trr, blr, brr;
1307 qNormalizeRadii(r, bd->radii.data(), &tlr, &trr, &blr, &brr);
1308 if (tlr.isNull() && trr.isNull() && blr.isNull() && brr.isNull())
1309 return QPainterPath();
1310
1311 const QRectF rect(r);
1312 const auto &borders = border()->borders;
1313 QPainterPath path;
1314 qreal curY = rect.y() + borders[TopEdge]/2.0;
1315 path.moveTo(rect.x() + tlr.width(), curY);
1316 path.lineTo(rect.right() - trr.width(), curY);
1317 qreal curX = rect.right() - borders[RightEdge]/2.0;
1318 path.arcTo(curX - 2*trr.width() + borders[RightEdge], curY,
1319 trr.width()*2 - borders[RightEdge], trr.height()*2 - borders[TopEdge], 90, -90);
1320
1321 path.lineTo(curX, rect.bottom() - brr.height());
1322 curY = rect.bottom() - borders[BottomEdge]/2.0;
1323 path.arcTo(curX - 2*brr.width() + borders[RightEdge], curY - 2*brr.height() + borders[BottomEdge],
1324 brr.width()*2 - borders[RightEdge], brr.height()*2 - borders[BottomEdge], 0, -90);
1325
1326 path.lineTo(rect.x() + blr.width(), curY);
1327 curX = rect.left() + borders[LeftEdge]/2.0;
1328 path.arcTo(curX, rect.bottom() - 2*blr.height() + borders[BottomEdge]/2.0,
1329 blr.width()*2 - borders[LeftEdge], blr.height()*2 - borders[BottomEdge], 270, -90);
1330
1331 path.lineTo(curX, rect.top() + tlr.height());
1332 path.arcTo(curX, rect.top() + borders[TopEdge]/2.0,
1333 tlr.width()*2 - borders[LeftEdge], tlr.height()*2 - borders[TopEdge], 180, -90);
1334
1335 path.closeSubpath();
1336 return path;
1337}
1338
1339/*! \internal
1340 Clip the painter to the border (in case we are using radius border)
1341 */
1342void QRenderRule::setClip(QPainter *p, const QRect &rect)
1343{
1344 if (clipset++)
1345 return;
1346 clipPath = borderClip(rect);
1347 if (!clipPath.isEmpty()) {
1348 p->save();
1349 p->setClipPath(clipPath, Qt::IntersectClip);
1350 }
1351}
1352
1353void QRenderRule::unsetClip(QPainter *p)
1354{
1355 if (--clipset)
1356 return;
1357 if (!clipPath.isEmpty())
1358 p->restore();
1359}
1360
1361void QRenderRule::drawBackground(QPainter *p, const QRect& rect, const QPoint& off)
1362{
1363 QBrush brush = hasBackground() ? background()->brush : QBrush();
1364 if (brush.style() == Qt::NoBrush)
1365 brush = defaultBackground;
1366
1367 if (brush.style() != Qt::NoBrush) {
1368 Origin origin = hasBackground() ? background()->clip : Origin_Border;
1369 // ### fix for gradients
1370 const QPainterPath &borderPath = borderClip(originRect(rect, origin));
1371 if (!borderPath.isEmpty()) {
1372 // Drawn instead of being used as clipping path for better visual quality
1373 bool wasAntialiased = p->renderHints() & QPainter::Antialiasing;
1374 p->setRenderHint(QPainter::Antialiasing);
1375 p->fillPath(borderPath, brush);
1376 p->setRenderHint(QPainter::Antialiasing, wasAntialiased);
1377 } else {
1378 p->fillRect(originRect(rect, origin), brush);
1379 }
1380 }
1381
1382 drawBackgroundImage(p, rect, off);
1383}
1384
1385void QRenderRule::drawFrame(QPainter *p, const QRect& rect)
1386{
1387 drawBackground(p, rect);
1388 if (hasBorder())
1389 drawBorder(p, borderRect(rect));
1390}
1391
1392void QRenderRule::drawImage(QPainter *p, const QRect &rect)
1393{
1394 if (!hasImage())
1395 return;
1396 QRect r = rect;
1397 // if an explicit width and height is set it must be honored
1398 // QIcon needs an overload taking two rects, one for the painting
1399 // area and one for the desired image size
1400 if (geo && geo->width != -1 && geo->height != -1) {
1401 const QSize sz = QSize(geo->width, geo->height).expandedTo(minimumContentsSize());
1402 r = QStyle::alignedRect(p->layoutDirection(), img->alignment, sz, r);
1403 }
1404 img->icon.paint(p, r, img->alignment);
1405}
1406
1407void QRenderRule::drawRule(QPainter *p, const QRect& rect)
1408{
1409 drawFrame(p, rect);
1410 drawImage(p, contentsRect(rect));
1411}
1412
1413// *shudder* , *horror*, *whoa* <-- what you might feel when you see the functions below
1414void QRenderRule::configurePalette(QPalette *p, QPalette::ColorRole fr, QPalette::ColorRole br)
1415{
1416 if (bg && bg->brush.style() != Qt::NoBrush) {
1417 if (br != QPalette::NoRole)
1418 p->setBrush(br, bg->brush);
1419 p->setBrush(QPalette::Window, bg->brush);
1420 if (bg->brush.style() == Qt::SolidPattern) {
1421 p->setBrush(QPalette::Light, bg->brush.color().lighter(115));
1422 p->setBrush(QPalette::Midlight, bg->brush.color().lighter(107));
1423 p->setBrush(QPalette::Dark, bg->brush.color().darker(150));
1424 p->setBrush(QPalette::Shadow, bg->brush.color().darker(300));
1425 }
1426 }
1427
1428 if (!hasPalette())
1429 return;
1430
1431 if (pal->foreground.style() != Qt::NoBrush) {
1432 if (fr != QPalette::NoRole)
1433 p->setBrush(fr, pal->foreground);
1434 p->setBrush(QPalette::WindowText, pal->foreground);
1435 p->setBrush(QPalette::Text, pal->foreground);
1436 }
1437 if (pal->selectionBackground.style() != Qt::NoBrush)
1438 p->setBrush(QPalette::Highlight, pal->selectionBackground);
1439 if (pal->selectionForeground.style() != Qt::NoBrush)
1440 p->setBrush(QPalette::HighlightedText, pal->selectionForeground);
1441 if (pal->alternateBackground.style() != Qt::NoBrush)
1442 p->setBrush(QPalette::AlternateBase, pal->alternateBackground);
1443}
1444
1445void setDefault(QPalette *palette, QPalette::ColorGroup group, QPalette::ColorRole role,
1446 const QBrush &defaultBrush, const QWidget *widget)
1447{
1448 const QPalette &widgetPalette = widget->palette();
1449 if (defaultBrush != Qt::NoBrush)
1450 palette->setBrush(group, role, defaultBrush);
1451 else
1452 palette->setBrush(group, role, widgetPalette.brush(group, role));
1453}
1454
1455void QRenderRule::configurePalette(QPalette *p, QPalette::ColorGroup cg, const QWidget *w, bool embedded)
1456{
1457 if (bg && bg->brush.style() != Qt::NoBrush) {
1458 p->setBrush(cg, QPalette::Base, bg->brush); // for windows, windowxp
1459 p->setBrush(cg, QPalette::Button, bg->brush); // for plastique
1460 p->setBrush(cg, w->backgroundRole(), bg->brush);
1461 p->setBrush(cg, QPalette::Window, bg->brush);
1462 }
1463
1464 if (embedded) {
1465 /* For embedded widgets (ComboBox, SpinBox and ScrollArea) we want the embedded widget
1466 * to be transparent when we have a transparent background or border image */
1467 if ((hasBackground() && background()->isTransparent())
1468 || (hasBorder() && border()->hasBorderImage() && !border()->borderImage()->pixmap.isNull()))
1469 p->setBrush(cg, w->backgroundRole(), Qt::NoBrush);
1470 }
1471
1472 if (!hasPalette())
1473 return;
1474
1475 if (pal->foreground.style() != Qt::NoBrush) {
1476 setDefault(p, cg, QPalette::ButtonText, pal->foreground, w);
1477 setDefault(p, cg, w->foregroundRole(), pal->foreground, w);
1478 setDefault(p, cg, QPalette::WindowText, pal->foreground, w);
1479 setDefault(p, cg, QPalette::Text, pal->foreground, w);
1480 QColor phColor(pal->foreground.color());
1481 phColor.setAlpha((phColor.alpha() + 1) / 2);
1482 QBrush placeholder = pal->foreground;
1483 placeholder.setColor(phColor);
1484 setDefault(p, cg, QPalette::PlaceholderText, placeholder, w);
1485 }
1486 if (pal->selectionBackground.style() != Qt::NoBrush)
1487 p->setBrush(cg, QPalette::Highlight, pal->selectionBackground);
1488 if (pal->selectionForeground.style() != Qt::NoBrush)
1489 p->setBrush(cg, QPalette::HighlightedText, pal->selectionForeground);
1490 if (pal->alternateBackground.style() != Qt::NoBrush)
1491 p->setBrush(cg, QPalette::AlternateBase, pal->alternateBackground);
1492 if (pal->placeholderForeground.style() != Qt::NoBrush)
1493 p->setBrush(cg, QPalette::PlaceholderText, pal->placeholderForeground);
1494 if (pal->accent.style() != Qt::NoBrush)
1495 p->setBrush(cg, QPalette::Accent, pal->accent);
1496}
1497
1498bool QRenderRule::hasModification() const
1499{
1500 return hasPalette() ||
1501 hasBackground() ||
1502 hasGradientBackground() ||
1503 !hasNativeBorder() ||
1504 !hasNativeOutline() ||
1505 hasBox() ||
1506 hasPosition() ||
1507 hasGeometry() ||
1508 hasImage() ||
1509 hasFont ||
1510 !styleHints.isEmpty();
1511}
1512
1513///////////////////////////////////////////////////////////////////////////////
1514// Style rules
1515#define OBJECT_PTR(x) (static_cast<QObject *>(x.ptr))
1516
1517static inline QObject *parentObject(const QObject *obj)
1518{
1519#if QT_CONFIG(tooltip)
1520 if (qobject_cast<const QTipLabel *>(obj) != nullptr) {
1521 QObject *p = qvariant_cast<QObject *>(obj->property("_q_stylesheet_parent"));
1522 if (p)
1523 return p;
1524 }
1525#endif
1526 return obj->parent();
1527}
1528
1529class QStyleSheetStyleSelector : public StyleSelector
1530{
1531public:
1532 QStyleSheetStyleSelector() { }
1533
1534 QStringList nodeNames(NodePtr node) const override
1535 {
1536 if (isNullNode(node))
1537 return QStringList();
1538 const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
1539#if QT_CONFIG(tooltip)
1540 if (metaObject == &QTipLabel::staticMetaObject)
1541 return QStringList("QToolTip"_L1);
1542#endif
1543 QStringList result;
1544 do {
1545 result += QString::fromLatin1(metaObject->className()).replace(u':', u'-');
1546 metaObject = metaObject->superClass();
1547 } while (metaObject != nullptr);
1548 return result;
1549 }
1550 QString attributeValue(NodePtr node, const QCss::AttributeSelector& aSelector) const override
1551 {
1552 if (isNullNode(node))
1553 return QString();
1554
1555 const QString &name = aSelector.name;
1556 QHash<QString, QString> &cache = m_attributeCache[OBJECT_PTR(node)];
1557 QHash<QString, QString>::const_iterator cacheIt = cache.constFind(name);
1558 if (cacheIt != cache.constEnd())
1559 return cacheIt.value();
1560
1561 QVariant value;
1562 QString valueStr;
1563 QObject *obj = OBJECT_PTR(node);
1564 const int propertyIndex = obj->metaObject()->indexOfProperty(name.toLatin1());
1565 if (propertyIndex == -1) {
1566 value = obj->property(name.toLatin1()); // might be a dynamic property
1567 if (!value.isValid()) {
1568 if (name == "class"_L1) {
1569 QString className = QString::fromLatin1(obj->metaObject()->className());
1570 if (className.contains(u':'))
1571 className.replace(u':', u'-');
1572 valueStr = className;
1573 } else if (name == "style"_L1) {
1574 QWidget *w = qobject_cast<QWidget *>(obj);
1575 QStyleSheetStyle *proxy = w ? qt_styleSheet(w->style()) : nullptr;
1576 if (proxy)
1577 valueStr = QString::fromLatin1(proxy->baseStyle()->metaObject()->className());
1578 }
1579 }
1580 } else {
1581 const QMetaProperty property = obj->metaObject()->property(propertyIndex);
1582 value = property.read(obj);
1583 // support Qt 5 selector syntax, which required the integer enum value
1584 if (property.isEnumType()) {
1585 bool isNumber;
1586 aSelector.value.toInt(&isNumber);
1587 if (isNumber)
1588 value.convert(QMetaType::fromType<int>());
1589 }
1590 }
1591 if (value.isValid()) {
1592 valueStr = (value.userType() == QMetaType::QStringList
1593 || value.userType() == QMetaType::QVariantList)
1594 ? value.toStringList().join(u' ')
1595 : value.toString();
1596 }
1597 cache[name] = valueStr;
1598 return valueStr;
1599 }
1600 bool nodeNameEquals(NodePtr node, const QString& nodeName) const override
1601 {
1602 if (isNullNode(node))
1603 return false;
1604 const QMetaObject *metaObject = OBJECT_PTR(node)->metaObject();
1605#if QT_CONFIG(tooltip)
1606 if (metaObject == &QTipLabel::staticMetaObject)
1607 return nodeName == "QToolTip"_L1;
1608#endif
1609 do {
1610 const auto *uc = reinterpret_cast<const char16_t *>(nodeName.constData());
1611 const auto *e = uc + nodeName.size();
1612 const uchar *c = (const uchar *)metaObject->className();
1613 while (*c && uc != e && (*uc == *c || (*c == ':' && *uc == '-'))) {
1614 ++uc;
1615 ++c;
1616 }
1617 if (uc == e && !*c)
1618 return true;
1619 metaObject = metaObject->superClass();
1620 } while (metaObject != nullptr);
1621 return false;
1622 }
1623 bool hasAttributes(NodePtr) const override
1624 { return true; }
1625 QStringList nodeIds(NodePtr node) const override
1626 { return isNullNode(node) ? QStringList() : QStringList(OBJECT_PTR(node)->objectName()); }
1627 bool isNullNode(NodePtr node) const override
1628 { return node.ptr == nullptr; }
1629 NodePtr parentNode(NodePtr node) const override
1630 { NodePtr n; n.ptr = isNullNode(node) ? nullptr : parentObject(OBJECT_PTR(node)); return n; }
1631 NodePtr previousSiblingNode(NodePtr) const override
1632 { NodePtr n; n.ptr = nullptr; return n; }
1633 NodePtr duplicateNode(NodePtr node) const override
1634 { return node; }
1635 void freeNode(NodePtr) const override
1636 { }
1637
1638private:
1639 mutable QHash<const QObject *, QHash<QString, QString> > m_attributeCache;
1640};
1641
1642QList<QCss::StyleRule> QStyleSheetStyle::styleRules(const QWidget *w) const
1643{
1644 QHash<const QObject *, QList<StyleRule>>::const_iterator cacheIt =
1645 styleSheetCaches->styleRulesCache.constFind(w);
1646 if (cacheIt != styleSheetCaches->styleRulesCache.constEnd())
1647 return cacheIt.value();
1648
1649 if (!initWidget(w))
1650 return {};
1651
1652 QStyleSheetStyleSelector styleSelector;
1653
1654 StyleSheet defaultSs;
1655 QHash<const void *, StyleSheet>::const_iterator defaultCacheIt = styleSheetCaches->styleSheetCache.constFind(baseStyle());
1656 if (defaultCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
1657 defaultSs = getDefaultStyleSheet();
1658 QStyle *bs = baseStyle();
1659 styleSheetCaches->styleSheetCache.insert(bs, defaultSs);
1660 QObject::connect(bs, &QStyle::destroyed, styleSheetCaches,
1661 &QStyleSheetStyleCaches::styleDestroyed);
1662 } else {
1663 defaultSs = defaultCacheIt.value();
1664 }
1665 styleSelector.styleSheets += defaultSs;
1666
1667 if (!qApp->styleSheet().isEmpty()) {
1668 StyleSheet appSs;
1669 QHash<const void *, StyleSheet>::const_iterator appCacheIt = styleSheetCaches->styleSheetCache.constFind(qApp);
1670 if (appCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
1671 QString ss = qApp->styleSheet();
1672 if (ss.startsWith("file:///"_L1))
1673 ss.remove(0, 8);
1674 parser.init(ss, qApp->styleSheet() != ss);
1675 if (Q_UNLIKELY(!parser.parse(&appSs)))
1676 qWarning("Could not parse application stylesheet");
1677 appSs.origin = StyleSheetOrigin_Inline;
1678 appSs.depth = 1;
1679 styleSheetCaches->styleSheetCache.insert(qApp, appSs);
1680 } else {
1681 appSs = appCacheIt.value();
1682 }
1683 styleSelector.styleSheets += appSs;
1684 }
1685
1686 QList<QCss::StyleSheet> objectSs;
1687 for (const QObject *o = w; o; o = parentObject(o)) {
1688 QString styleSheet = o->property("styleSheet").toString();
1689 if (styleSheet.isEmpty())
1690 continue;
1691 StyleSheet ss;
1692 QHash<const void *, StyleSheet>::const_iterator objCacheIt = styleSheetCaches->styleSheetCache.constFind(o);
1693 if (objCacheIt == styleSheetCaches->styleSheetCache.constEnd()) {
1694 parser.init(styleSheet);
1695 if (!parser.parse(&ss)) {
1696 parser.init("* {"_L1 + styleSheet + u'}');
1697 if (Q_UNLIKELY(!parser.parse(&ss)))
1698 qWarning() << "Could not parse stylesheet of object" << o;
1699 }
1700 ss.origin = StyleSheetOrigin_Inline;
1701 styleSheetCaches->styleSheetCache.insert(o, ss);
1702 } else {
1703 ss = objCacheIt.value();
1704 }
1705 objectSs.append(ss);
1706 }
1707
1708 for (int i = 0; i < objectSs.size(); i++)
1709 objectSs[i].depth = objectSs.size() - i + 2;
1710
1711 styleSelector.styleSheets += objectSs;
1712
1713 StyleSelector::NodePtr n;
1714 n.ptr = const_cast<QWidget *>(w);
1715 QList<QCss::StyleRule> rules = styleSelector.styleRulesForNode(n);
1716 styleSheetCaches->styleRulesCache.insert(w, rules);
1717 return rules;
1718}
1719
1720/////////////////////////////////////////////////////////////////////////////////////////
1721// Rendering rules
1722static QList<Declaration> declarations(const QList<StyleRule> &styleRules, QLatin1StringView part,
1723 quint64 pseudoClass = PseudoClass_Unspecified)
1724{
1725 QList<Declaration> decls;
1726 for (const auto &rule : styleRules) {
1727 const Selector &selector = rule.selectors.at(0);
1728 // Rules with pseudo elements don't cascade. This is an intentional
1729 // diversion for CSS
1730 if (part.compare(selector.pseudoElement(), Qt::CaseInsensitive) != 0)
1731 continue;
1732 quint64 negated = 0;
1733 quint64 cssClass = selector.pseudoClass(&negated);
1734 if ((pseudoClass == PseudoClass_Any) || (cssClass == PseudoClass_Unspecified)
1735 || ((((cssClass & pseudoClass) == cssClass)) && ((negated & pseudoClass) == 0)))
1736 decls += rule.declarations;
1737 }
1738 return decls;
1739}
1740
1741int QStyleSheetStyle::nativeFrameWidth(const QWidget *w)
1742{
1743 QStyle *base = baseStyle();
1744
1745#if QT_CONFIG(spinbox)
1746 if (qobject_cast<const QAbstractSpinBox *>(w))
1747 return base->pixelMetric(QStyle::PM_SpinBoxFrameWidth, nullptr, w);
1748#endif
1749
1750#if QT_CONFIG(combobox)
1751 if (qobject_cast<const QComboBox *>(w))
1752 return base->pixelMetric(QStyle::PM_ComboBoxFrameWidth, nullptr, w);
1753#endif
1754
1755#if QT_CONFIG(menu)
1756 if (qobject_cast<const QMenu *>(w))
1757 return base->pixelMetric(QStyle::PM_MenuPanelWidth, nullptr, w);
1758#endif
1759
1760#if QT_CONFIG(menubar)
1761 if (qobject_cast<const QMenuBar *>(w))
1762 return base->pixelMetric(QStyle::PM_MenuBarPanelWidth, nullptr, w);
1763#endif
1764#ifndef QT_NO_FRAME
1765 if (const QFrame *frame = qobject_cast<const QFrame *>(w)) {
1766 if (frame->frameShape() == QFrame::NoFrame)
1767 return 0;
1768 }
1769#endif
1770
1771 if (w->metaObject() == &QTipLabel::staticMetaObject)
1772 return base->pixelMetric(QStyle::PM_ToolTipLabelFrameWidth, nullptr, w);
1773
1774 return base->pixelMetric(QStyle::PM_DefaultFrameWidth, nullptr, w);
1775}
1776
1777static quint64 pseudoClass(QStyle::State state)
1778{
1779 quint64 pc = 0;
1780 if (state & QStyle::State_Enabled) {
1781 pc |= PseudoClass_Enabled;
1782 if (state & QStyle::State_MouseOver)
1783 pc |= PseudoClass_Hover;
1784 } else {
1785 pc |= PseudoClass_Disabled;
1786 }
1787 if (state & QStyle::State_Active)
1788 pc |= PseudoClass_Active;
1789 if (state & QStyle::State_Window)
1790 pc |= PseudoClass_Window;
1791 if (state & QStyle::State_Sunken)
1792 pc |= PseudoClass_Pressed;
1793 if (state & QStyle::State_HasFocus)
1794 pc |= PseudoClass_Focus;
1795 if (state & QStyle::State_On)
1796 pc |= (PseudoClass_On | PseudoClass_Checked);
1797 if (state & QStyle::State_Off)
1798 pc |= (PseudoClass_Off | PseudoClass_Unchecked);
1799 if (state & QStyle::State_NoChange)
1800 pc |= PseudoClass_Indeterminate;
1801 if (state & QStyle::State_Selected)
1802 pc |= PseudoClass_Selected;
1803 if (state & QStyle::State_Horizontal)
1804 pc |= PseudoClass_Horizontal;
1805 else
1806 pc |= PseudoClass_Vertical;
1807 if (state & (QStyle::State_Open | QStyle::State_On | QStyle::State_Sunken))
1808 pc |= PseudoClass_Open;
1809 else
1810 pc |= PseudoClass_Closed;
1811 if (state & QStyle::State_Children)
1812 pc |= PseudoClass_Children;
1813 if (state & QStyle::State_Sibling)
1814 pc |= PseudoClass_Sibling;
1815 if (state & QStyle::State_ReadOnly)
1816 pc |= PseudoClass_ReadOnly;
1817 if (state & QStyle::State_Item)
1818 pc |= PseudoClass_Item;
1819 return pc;
1820}
1821
1822static void qt_check_if_internal_widget(const QWidget **w, int *element)
1823{
1824#if !QT_CONFIG(dockwidget)
1825 Q_UNUSED(w);
1826 Q_UNUSED(element);
1827#else
1828 if (*w && qstrcmp((*w)->metaObject()->className(), "QDockWidgetTitleButton") == 0) {
1829 if ((*w)->objectName() == "qt_dockwidget_closebutton"_L1)
1830 *element = PseudoElement_DockWidgetCloseButton;
1831 else if ((*w)->objectName() == "qt_dockwidget_floatbutton"_L1)
1832 *element = PseudoElement_DockWidgetFloatButton;
1833 *w = (*w)->parentWidget();
1834 }
1835#endif
1836}
1837
1838QRenderRule QStyleSheetStyle::renderRule(const QWidget *w, int element, quint64 state) const
1839{
1840 qt_check_if_internal_widget(&w, &element);
1841 QHash<quint64, QRenderRule> &cache = styleSheetCaches->renderRulesCache[w][element];
1842 QHash<quint64, QRenderRule>::const_iterator cacheIt = cache.constFind(state);
1843 if (cacheIt != cache.constEnd())
1844 return cacheIt.value();
1845
1846 if (!initWidget(w))
1847 return QRenderRule();
1848
1849 quint64 stateMask = 0;
1850 const QList<StyleRule> rules = styleRules(w);
1851 for (const auto &rule : rules) {
1852 const Selector &selector = rule.selectors.at(0);
1853 quint64 negated = 0;
1854 stateMask |= selector.pseudoClass(&negated);
1855 stateMask |= negated;
1856 }
1857
1858 cacheIt = cache.constFind(state & stateMask);
1859 if (cacheIt != cache.constEnd()) {
1860 QRenderRule newRule = cacheIt.value();
1861 cache[state] = newRule;
1862 return newRule;
1863 }
1864
1865
1866 const auto part = QLatin1StringView(knownPseudoElements[element].name);
1867 QList<Declaration> decls = declarations(rules, part, state);
1868 QRenderRule newRule(decls, w);
1869 cache[state] = newRule;
1870 if ((state & stateMask) != state)
1871 cache[state&stateMask] = newRule;
1872 return newRule;
1873}
1874
1875QRenderRule QStyleSheetStyle::renderRule(const QWidget *w, const QStyleOption *opt, int pseudoElement) const
1876{
1877 quint64 extraClass = 0;
1878 QStyle::State state = opt ? opt->state : QStyle::State(QStyle::State_None);
1879
1880 if (const QStyleOptionComplex *complex = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
1881 if (pseudoElement != PseudoElement_None) {
1882 // if not an active subcontrol, just pass enabled/disabled
1883 QStyle::SubControl subControl = knownPseudoElements[pseudoElement].subControl;
1884
1885 if (!(complex->activeSubControls & subControl))
1886 state &= (QStyle::State_Enabled | QStyle::State_Horizontal | QStyle::State_HasFocus);
1887 }
1888
1889 switch (pseudoElement) {
1890 case PseudoElement_ComboBoxDropDown:
1891 case PseudoElement_ComboBoxArrow:
1892 state |= (complex->state & (QStyle::State_On|QStyle::State_ReadOnly));
1893 break;
1894 case PseudoElement_SpinBoxUpButton:
1895 case PseudoElement_SpinBoxDownButton:
1896 case PseudoElement_SpinBoxUpArrow:
1897 case PseudoElement_SpinBoxDownArrow:
1898#if QT_CONFIG(spinbox)
1899 if (const QStyleOptionSpinBox *sb = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
1900 bool on = false;
1901 bool up = pseudoElement == PseudoElement_SpinBoxUpButton
1902 || pseudoElement == PseudoElement_SpinBoxUpArrow;
1903 if ((sb->stepEnabled & QAbstractSpinBox::StepUpEnabled) && up)
1904 on = true;
1905 else if ((sb->stepEnabled & QAbstractSpinBox::StepDownEnabled) && !up)
1906 on = true;
1907 state |= (on ? QStyle::State_On : QStyle::State_Off);
1908 }
1909#endif // QT_CONFIG(spinbox)
1910 break;
1911 case PseudoElement_GroupBoxTitle:
1912 state |= (complex->state & (QStyle::State_MouseOver | QStyle::State_Sunken));
1913 break;
1914 case PseudoElement_ToolButtonMenu:
1915 case PseudoElement_ToolButtonMenuArrow:
1916 case PseudoElement_ToolButtonMenuIndicator:
1917 state |= complex->state & QStyle::State_MouseOver;
1918 if (complex->state & QStyle::State_Sunken ||
1919 complex->activeSubControls & QStyle::SC_ToolButtonMenu)
1920 state |= QStyle::State_Sunken;
1921 break;
1922 case PseudoElement_SliderGroove:
1923 state |= complex->state & QStyle::State_MouseOver;
1924 break;
1925 default:
1926 break;
1927 }
1928
1929 if (const QStyleOptionComboBox *combo = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
1930 // QStyle::State_On is set when the popup is being shown
1931 // Propagate EditField Pressed state
1932 if (pseudoElement == PseudoElement_None
1933 && (complex->activeSubControls & QStyle::SC_ComboBoxEditField)
1934 && (!(state & QStyle::State_MouseOver))) {
1935 state |= QStyle::State_Sunken;
1936 }
1937
1938 if (!combo->frame)
1939 extraClass |= PseudoClass_Frameless;
1940 if (!combo->editable)
1941 extraClass |= PseudoClass_ReadOnly;
1942 else
1943 extraClass |= PseudoClass_Editable;
1944#if QT_CONFIG(spinbox)
1945 } else if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
1946 if (!spin->frame)
1947 extraClass |= PseudoClass_Frameless;
1948#endif // QT_CONFIG(spinbox)
1949 } else if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
1950 if (gb->features & QStyleOptionFrame::Flat)
1951 extraClass |= PseudoClass_Flat;
1952 if (gb->lineWidth == 0)
1953 extraClass |= PseudoClass_Frameless;
1954 } else if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
1955 if (tb->titleBarState & Qt::WindowMinimized) {
1956 extraClass |= PseudoClass_Minimized;
1957 }
1958 else if (tb->titleBarState & Qt::WindowMaximized)
1959 extraClass |= PseudoClass_Maximized;
1960 }
1961 } else {
1962 // handle simple style options
1963 if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
1964 if (mi->menuItemType == QStyleOptionMenuItem::DefaultItem)
1965 extraClass |= PseudoClass_Default;
1966 if (mi->checkType == QStyleOptionMenuItem::Exclusive)
1967 extraClass |= PseudoClass_Exclusive;
1968 else if (mi->checkType == QStyleOptionMenuItem::NonExclusive)
1969 extraClass |= PseudoClass_NonExclusive;
1970 if (mi->checkType != QStyleOptionMenuItem::NotCheckable)
1971 extraClass |= (mi->checked) ? (PseudoClass_On|PseudoClass_Checked)
1972 : (PseudoClass_Off|PseudoClass_Unchecked);
1973 } else if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
1974 if (hdr->position == QStyleOptionHeader::OnlyOneSection)
1975 extraClass |= PseudoClass_OnlyOne;
1976 else if (hdr->position == QStyleOptionHeader::Beginning)
1977 extraClass |= PseudoClass_First;
1978 else if (hdr->position == QStyleOptionHeader::End)
1979 extraClass |= PseudoClass_Last;
1980 else if (hdr->position == QStyleOptionHeader::Middle)
1981 extraClass |= PseudoClass_Middle;
1982
1983 if (hdr->selectedPosition == QStyleOptionHeader::NextAndPreviousAreSelected)
1984 extraClass |= (PseudoClass_NextSelected | PseudoClass_PreviousSelected);
1985 else if (hdr->selectedPosition == QStyleOptionHeader::NextIsSelected)
1986 extraClass |= PseudoClass_NextSelected;
1987 else if (hdr->selectedPosition == QStyleOptionHeader::PreviousIsSelected)
1988 extraClass |= PseudoClass_PreviousSelected;
1989#if QT_CONFIG(tabwidget)
1990 } else if (const QStyleOptionTabWidgetFrame *tab = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
1991 switch (tab->shape) {
1992 case QTabBar::RoundedNorth:
1993 case QTabBar::TriangularNorth:
1994 extraClass |= PseudoClass_Top;
1995 break;
1996 case QTabBar::RoundedSouth:
1997 case QTabBar::TriangularSouth:
1998 extraClass |= PseudoClass_Bottom;
1999 break;
2000 case QTabBar::RoundedEast:
2001 case QTabBar::TriangularEast:
2002 extraClass |= PseudoClass_Right;
2003 break;
2004 case QTabBar::RoundedWest:
2005 case QTabBar::TriangularWest:
2006 extraClass |= PseudoClass_Left;
2007 break;
2008 default:
2009 break;
2010 }
2011#endif
2012#if QT_CONFIG(tabbar)
2013 } else if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
2014 if (tab->position == QStyleOptionTab::OnlyOneTab)
2015 extraClass |= PseudoClass_OnlyOne;
2016 else if (tab->position == QStyleOptionTab::Beginning)
2017 extraClass |= PseudoClass_First;
2018 else if (tab->position == QStyleOptionTab::End)
2019 extraClass |= PseudoClass_Last;
2020 else if (tab->position == QStyleOptionTab::Middle)
2021 extraClass |= PseudoClass_Middle;
2022
2023 if (tab->selectedPosition == QStyleOptionTab::NextIsSelected)
2024 extraClass |= PseudoClass_NextSelected;
2025 else if (tab->selectedPosition == QStyleOptionTab::PreviousIsSelected)
2026 extraClass |= PseudoClass_PreviousSelected;
2027
2028 switch (tab->shape) {
2029 case QTabBar::RoundedNorth:
2030 case QTabBar::TriangularNorth:
2031 extraClass |= PseudoClass_Top;
2032 break;
2033 case QTabBar::RoundedSouth:
2034 case QTabBar::TriangularSouth:
2035 extraClass |= PseudoClass_Bottom;
2036 break;
2037 case QTabBar::RoundedEast:
2038 case QTabBar::TriangularEast:
2039 extraClass |= PseudoClass_Right;
2040 break;
2041 case QTabBar::RoundedWest:
2042 case QTabBar::TriangularWest:
2043 extraClass |= PseudoClass_Left;
2044 break;
2045 default:
2046 break;
2047 }
2048#endif // QT_CONFIG(tabbar)
2049 } else if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
2050 if (btn->features & QStyleOptionButton::Flat)
2051 extraClass |= PseudoClass_Flat;
2052 if (btn->features & QStyleOptionButton::DefaultButton)
2053 extraClass |= PseudoClass_Default;
2054 } else if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
2055 if (frm->lineWidth == 0)
2056 extraClass |= PseudoClass_Frameless;
2057 if (frm->features & QStyleOptionFrame::Flat)
2058 extraClass |= PseudoClass_Flat;
2059 }
2060#if QT_CONFIG(toolbar)
2061 else if (const QStyleOptionToolBar *tb = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
2062 if (tb->toolBarArea == Qt::LeftToolBarArea)
2063 extraClass |= PseudoClass_Left;
2064 else if (tb->toolBarArea == Qt::RightToolBarArea)
2065 extraClass |= PseudoClass_Right;
2066 else if (tb->toolBarArea == Qt::TopToolBarArea)
2067 extraClass |= PseudoClass_Top;
2068 else if (tb->toolBarArea == Qt::BottomToolBarArea)
2069 extraClass |= PseudoClass_Bottom;
2070
2071 if (tb->positionWithinLine == QStyleOptionToolBar::Beginning)
2072 extraClass |= PseudoClass_First;
2073 else if (tb->positionWithinLine == QStyleOptionToolBar::Middle)
2074 extraClass |= PseudoClass_Middle;
2075 else if (tb->positionWithinLine == QStyleOptionToolBar::End)
2076 extraClass |= PseudoClass_Last;
2077 else if (tb->positionWithinLine == QStyleOptionToolBar::OnlyOne)
2078 extraClass |= PseudoClass_OnlyOne;
2079 }
2080#endif // QT_CONFIG(toolbar)
2081#if QT_CONFIG(toolbox)
2082 else if (const QStyleOptionToolBox *tb = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
2083 if (tb->position == QStyleOptionToolBox::OnlyOneTab)
2084 extraClass |= PseudoClass_OnlyOne;
2085 else if (tb->position == QStyleOptionToolBox::Beginning)
2086 extraClass |= PseudoClass_First;
2087 else if (tb->position == QStyleOptionToolBox::End)
2088 extraClass |= PseudoClass_Last;
2089 else if (tb->position == QStyleOptionToolBox::Middle)
2090 extraClass |= PseudoClass_Middle;
2091
2092 if (tb->selectedPosition == QStyleOptionToolBox::NextIsSelected)
2093 extraClass |= PseudoClass_NextSelected;
2094 else if (tb->selectedPosition == QStyleOptionToolBox::PreviousIsSelected)
2095 extraClass |= PseudoClass_PreviousSelected;
2096 }
2097#endif // QT_CONFIG(toolbox)
2098#if QT_CONFIG(dockwidget)
2099 else if (const QStyleOptionDockWidget *dw = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
2100 if (dw->verticalTitleBar)
2101 extraClass |= PseudoClass_Vertical;
2102 else
2103 extraClass |= PseudoClass_Horizontal;
2104 if (dw->closable)
2105 extraClass |= PseudoClass_Closable;
2106 if (dw->floatable)
2107 extraClass |= PseudoClass_Floatable;
2108 if (dw->movable)
2109 extraClass |= PseudoClass_Movable;
2110 }
2111#endif // QT_CONFIG(dockwidget)
2112#if QT_CONFIG(itemviews)
2113 else if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
2114 if (vopt->features & QStyleOptionViewItem::Alternate)
2115 extraClass |= PseudoClass_Alternate;
2116 if (vopt->viewItemPosition == QStyleOptionViewItem::OnlyOne)
2117 extraClass |= PseudoClass_OnlyOne;
2118 else if (vopt->viewItemPosition == QStyleOptionViewItem::Beginning)
2119 extraClass |= PseudoClass_First;
2120 else if (vopt->viewItemPosition == QStyleOptionViewItem::End)
2121 extraClass |= PseudoClass_Last;
2122 else if (vopt->viewItemPosition == QStyleOptionViewItem::Middle)
2123 extraClass |= PseudoClass_Middle;
2124
2125 }
2126#endif
2127#if QT_CONFIG(textedit)
2128 else if (const QPlainTextEdit *edit = qobject_cast<const QPlainTextEdit *>(w))
2129 extraClass |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
2130 else if (const QTextEdit *edit = qobject_cast<const QTextEdit *>(w))
2131 extraClass |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
2132#endif
2133#if QT_CONFIG(lineedit)
2134 // LineEdit sets Sunken flag to indicate Sunken frame (argh)
2135 if (const QLineEdit *lineEdit = qobject_cast<const QLineEdit *>(w)) {
2136 state &= ~QStyle::State_Sunken;
2137 if (lineEdit->hasFrame()) {
2138 extraClass &= ~PseudoClass_Frameless;
2139 } else {
2140 extraClass |= PseudoClass_Frameless;
2141 }
2142 } else
2143#endif
2144 if (const QFrame *frm = qobject_cast<const QFrame *>(w)) {
2145 if (frm->lineWidth() == 0)
2146 extraClass |= PseudoClass_Frameless;
2147 }
2148 }
2149
2150 return renderRule(w, pseudoElement, pseudoClass(state) | extraClass);
2151}
2152
2153bool QStyleSheetStyle::hasStyleRule(const QWidget *w, int part) const
2154{
2155 QHash<int, bool> &cache = styleSheetCaches->hasStyleRuleCache[w];
2156 QHash<int, bool>::const_iterator cacheIt = cache.constFind(part);
2157 if (cacheIt != cache.constEnd())
2158 return cacheIt.value();
2159
2160 if (!initWidget(w))
2161 return false;
2162
2163 const QList<StyleRule> &rules = styleRules(w);
2164 if (part == PseudoElement_None) {
2165 bool result = w && !rules.isEmpty();
2166 cache[part] = result;
2167 return result;
2168 }
2169
2170 const auto pseudoElement = QLatin1StringView(knownPseudoElements[part].name);
2171 for (const auto &rule : rules) {
2172 const Selector &selector = rule.selectors.at(0);
2173 if (pseudoElement.compare(selector.pseudoElement(), Qt::CaseInsensitive) == 0) {
2174 cache[part] = true;
2175 return true;
2176 }
2177 }
2178
2179 cache[part] = false;
2180 return false;
2181}
2182
2183static Origin defaultOrigin(int pe)
2184{
2185 switch (pe) {
2186 case PseudoElement_ScrollBarAddPage:
2187 case PseudoElement_ScrollBarSubPage:
2188 case PseudoElement_ScrollBarAddLine:
2189 case PseudoElement_ScrollBarSubLine:
2190 case PseudoElement_ScrollBarFirst:
2191 case PseudoElement_ScrollBarLast:
2192 case PseudoElement_GroupBoxTitle:
2193 case PseudoElement_GroupBoxIndicator: // never used
2194 case PseudoElement_ToolButtonMenu:
2195 case PseudoElement_SliderAddPage:
2196 case PseudoElement_SliderSubPage:
2197 return Origin_Border;
2198
2199 case PseudoElement_SpinBoxUpButton:
2200 case PseudoElement_SpinBoxDownButton:
2201 case PseudoElement_PushButtonMenuIndicator:
2202 case PseudoElement_ComboBoxDropDown:
2203 case PseudoElement_ToolButtonMenuIndicator:
2204 case PseudoElement_MenuCheckMark:
2205 case PseudoElement_MenuIcon:
2206 case PseudoElement_MenuRightArrow:
2207 return Origin_Padding;
2208
2209 case PseudoElement_Indicator:
2210 case PseudoElement_ExclusiveIndicator:
2211 case PseudoElement_ComboBoxArrow:
2212 case PseudoElement_ScrollBarSlider:
2213 case PseudoElement_ScrollBarUpArrow:
2214 case PseudoElement_ScrollBarDownArrow:
2215 case PseudoElement_ScrollBarLeftArrow:
2216 case PseudoElement_ScrollBarRightArrow:
2217 case PseudoElement_SpinBoxUpArrow:
2218 case PseudoElement_SpinBoxDownArrow:
2219 case PseudoElement_ToolButtonMenuArrow:
2220 case PseudoElement_HeaderViewUpArrow:
2221 case PseudoElement_HeaderViewDownArrow:
2222 case PseudoElement_SliderGroove:
2223 case PseudoElement_SliderHandle:
2224 return Origin_Content;
2225
2226 default:
2227 return Origin_Margin;
2228 }
2229}
2230
2231static Qt::Alignment defaultPosition(int pe)
2232{
2233 switch (pe) {
2234 case PseudoElement_Indicator:
2235 case PseudoElement_ExclusiveIndicator:
2236 case PseudoElement_MenuCheckMark:
2237 case PseudoElement_MenuIcon:
2238 return Qt::AlignLeft | Qt::AlignVCenter;
2239
2240 case PseudoElement_ScrollBarAddLine:
2241 case PseudoElement_ScrollBarLast:
2242 case PseudoElement_SpinBoxDownButton:
2243 case PseudoElement_ToolButtonMenuIndicator:
2244 return Qt::AlignRight | Qt::AlignBottom;
2245
2246 case PseudoElement_PushButtonMenuIndicator:
2247 return Qt::AlignRight | Qt::AlignVCenter; // Center vertically to align with other styles
2248
2249 case PseudoElement_ScrollBarSubLine:
2250 case PseudoElement_ScrollBarFirst:
2251 case PseudoElement_SpinBoxUpButton:
2252 case PseudoElement_ComboBoxDropDown:
2253 case PseudoElement_ToolButtonMenu:
2254 case PseudoElement_DockWidgetCloseButton:
2255 case PseudoElement_DockWidgetFloatButton:
2256 return Qt::AlignRight | Qt::AlignTop;
2257
2258 case PseudoElement_ScrollBarUpArrow:
2259 case PseudoElement_ScrollBarDownArrow:
2260 case PseudoElement_ScrollBarLeftArrow:
2261 case PseudoElement_ScrollBarRightArrow:
2262 case PseudoElement_SpinBoxUpArrow:
2263 case PseudoElement_SpinBoxDownArrow:
2264 case PseudoElement_ComboBoxArrow:
2265 case PseudoElement_DownArrow:
2266 case PseudoElement_UpArrow:
2267 case PseudoElement_LeftArrow:
2268 case PseudoElement_RightArrow:
2269 case PseudoElement_ToolButtonMenuArrow:
2270 case PseudoElement_SliderGroove:
2271 return Qt::AlignCenter;
2272
2273 case PseudoElement_GroupBoxTitle:
2274 case PseudoElement_GroupBoxIndicator: // never used
2275 return Qt::AlignLeft | Qt::AlignTop;
2276
2277 case PseudoElement_HeaderViewUpArrow:
2278 case PseudoElement_HeaderViewDownArrow:
2279 case PseudoElement_MenuRightArrow:
2280 return Qt::AlignRight | Qt::AlignVCenter;
2281
2282 default:
2283 return { };
2284 }
2285}
2286
2287QSize QStyleSheetStyle::defaultSize(const QWidget *w, QSize sz, const QRect& rect, int pe) const
2288{
2289 QStyle *base = baseStyle();
2290
2291 switch (pe) {
2292 case PseudoElement_Indicator:
2293 case PseudoElement_MenuCheckMark:
2294 if (sz.width() == -1)
2295 sz.setWidth(base->pixelMetric(PM_IndicatorWidth, nullptr, w));
2296 if (sz.height() == -1)
2297 sz.setHeight(base->pixelMetric(PM_IndicatorHeight, nullptr, w));
2298 break;
2299
2300 case PseudoElement_ExclusiveIndicator:
2301 case PseudoElement_GroupBoxIndicator:
2302 if (sz.width() == -1)
2303 sz.setWidth(base->pixelMetric(PM_ExclusiveIndicatorWidth, nullptr, w));
2304 if (sz.height() == -1)
2305 sz.setHeight(base->pixelMetric(PM_ExclusiveIndicatorHeight, nullptr, w));
2306 break;
2307
2308 case PseudoElement_PushButtonMenuIndicator: {
2309 // Reduce size of indicator to align with other styles
2310 constexpr int sizeReduction = 6;
2311
2312 const int pm = base->pixelMetric(PM_MenuButtonIndicator, nullptr, w);
2313 if (sz.width() == -1)
2314 sz.setWidth(pm - sizeReduction);
2315 if (sz.height() == -1)
2316 sz.setHeight(pm - sizeReduction);
2317 }
2318 break;
2319
2320 case PseudoElement_ComboBoxDropDown:
2321 if (sz.width() == -1)
2322 sz.setWidth(16);
2323 break;
2324
2325 case PseudoElement_ComboBoxArrow:
2326 case PseudoElement_DownArrow:
2327 case PseudoElement_UpArrow:
2328 case PseudoElement_LeftArrow:
2329 case PseudoElement_RightArrow:
2330 case PseudoElement_ToolButtonMenuArrow:
2331 case PseudoElement_ToolButtonMenuIndicator:
2332 case PseudoElement_MenuRightArrow:
2333 if (sz.width() == -1)
2334 sz.setWidth(13);
2335 if (sz.height() == -1)
2336 sz.setHeight(13);
2337 break;
2338
2339 case PseudoElement_SpinBoxUpButton:
2340 case PseudoElement_SpinBoxDownButton:
2341 if (sz.width() == -1)
2342 sz.setWidth(16);
2343 if (sz.height() == -1)
2344 sz.setHeight(rect.height()/2);
2345 break;
2346
2347 case PseudoElement_ToolButtonMenu:
2348 if (sz.width() == -1)
2349 sz.setWidth(base->pixelMetric(PM_MenuButtonIndicator, nullptr, w));
2350 break;
2351
2352 case PseudoElement_HeaderViewUpArrow:
2353 case PseudoElement_HeaderViewDownArrow: {
2354 int pm = base->pixelMetric(PM_HeaderMargin, nullptr, w);
2355 if (sz.width() == -1)
2356 sz.setWidth(pm);
2357 if (sz.height() == 1)
2358 sz.setHeight(pm);
2359 break;
2360 }
2361
2362 case PseudoElement_ScrollBarFirst:
2363 case PseudoElement_ScrollBarLast:
2364 case PseudoElement_ScrollBarAddLine:
2365 case PseudoElement_ScrollBarSubLine:
2366 case PseudoElement_ScrollBarSlider: {
2367 int pm = pixelMetric(QStyle::PM_ScrollBarExtent, nullptr, w);
2368 if (sz.width() == -1)
2369 sz.setWidth(pm);
2370 if (sz.height() == -1)
2371 sz.setHeight(pm);
2372 break;
2373 }
2374
2375 case PseudoElement_DockWidgetCloseButton:
2376 case PseudoElement_DockWidgetFloatButton: {
2377 int iconSize = pixelMetric(PM_SmallIconSize, nullptr, w);
2378 return QSize(iconSize, iconSize);
2379 }
2380
2381 default:
2382 break;
2383 }
2384
2385 // expand to rectangle
2386 if (sz.height() == -1)
2387 sz.setHeight(rect.height());
2388 if (sz.width() == -1)
2389 sz.setWidth(rect.width());
2390
2391 return sz;
2392}
2393
2394static PositionMode defaultPositionMode(int pe)
2395{
2396 switch (pe) {
2397 case PseudoElement_ScrollBarFirst:
2398 case PseudoElement_ScrollBarLast:
2399 case PseudoElement_ScrollBarAddLine:
2400 case PseudoElement_ScrollBarSubLine:
2401 case PseudoElement_ScrollBarAddPage:
2402 case PseudoElement_ScrollBarSubPage:
2403 case PseudoElement_ScrollBarSlider:
2404 case PseudoElement_SliderGroove:
2405 case PseudoElement_SliderHandle:
2406 case PseudoElement_TabWidgetPane:
2407 return PositionMode_Absolute;
2408 default:
2409 return PositionMode_Static;
2410 }
2411}
2412
2413QRect QStyleSheetStyle::positionRect(const QWidget *w, const QRenderRule &rule2, int pe,
2414 const QRect &originRect, Qt::LayoutDirection dir) const
2415{
2416 const QStyleSheetPositionData *p = rule2.position();
2417 PositionMode mode = (p && p->mode != PositionMode_Unknown) ? p->mode : defaultPositionMode(pe);
2418 Qt::Alignment position = (p && p->position != 0) ? p->position : defaultPosition(pe);
2419 QRect r;
2420
2421 if (mode != PositionMode_Absolute) {
2422 QSize sz = defaultSize(w, rule2.size(), originRect, pe);
2423 sz = sz.expandedTo(rule2.minimumContentsSize());
2424 r = QStyle::alignedRect(dir, position, sz, originRect);
2425 if (p) {
2426 int left = p->left ? p->left : -p->right;
2427 int top = p->top ? p->top : -p->bottom;
2428 r.translate(dir == Qt::LeftToRight ? left : -left, top);
2429 }
2430 } else {
2431 r = p ? originRect.adjusted(dir == Qt::LeftToRight ? p->left : p->right, p->top,
2432 dir == Qt::LeftToRight ? -p->right : -p->left, -p->bottom)
2433 : originRect;
2434 if (rule2.hasContentsSize()) {
2435 QSize sz = rule2.size().expandedTo(rule2.minimumContentsSize());
2436 if (sz.width() == -1) sz.setWidth(r.width());
2437 if (sz.height() == -1) sz.setHeight(r.height());
2438 r = QStyle::alignedRect(dir, position, sz, r);
2439 }
2440 }
2441 return r;
2442}
2443
2444QRect QStyleSheetStyle::positionRect(const QWidget *w, const QRenderRule& rule1, const QRenderRule& rule2, int pe,
2445 const QRect& rect, Qt::LayoutDirection dir) const
2446{
2447 const QStyleSheetPositionData *p = rule2.position();
2448 Origin origin = (p && p->origin != Origin_Unknown) ? p->origin : defaultOrigin(pe);
2449 QRect originRect = rule1.originRect(rect, origin);
2450 return positionRect(w, rule2, pe, originRect, dir);
2451}
2452
2453
2454/** \internal
2455 For widget that have an embedded widget (such as combobox) return that embedded widget.
2456 otherwise return the widget itself
2457 */
2458static QWidget *embeddedWidget(QWidget *w)
2459{
2460#if QT_CONFIG(combobox)
2461 if (QComboBox *cmb = qobject_cast<QComboBox *>(w)) {
2462 if (cmb->isEditable())
2463 return cmb->lineEdit();
2464 else
2465 return cmb;
2466 }
2467#endif
2468
2469#if QT_CONFIG(spinbox)
2470 if (QAbstractSpinBox *sb = qobject_cast<QAbstractSpinBox *>(w))
2471 return sb->findChild<QLineEdit *>();
2472#endif
2473
2474#if QT_CONFIG(scrollarea)
2475 if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w))
2476 return sa->viewport();
2477#endif
2478
2479 return w;
2480}
2481
2482/** \internal
2483 Returns the widget whose style rules apply to \a w.
2484
2485 When \a w is an embedded widget, this is the container widget.
2486 For example, if w is a line edit embedded in a combobox, this returns the combobox.
2487 When \a w is not embedded, this function return \a w itself.
2488
2489*/
2490static const QWidget *containerWidget(const QWidget *w)
2491{
2492#if QT_CONFIG(lineedit)
2493 if (qobject_cast<const QLineEdit *>(w)) {
2494 //if the QLineEdit is an embeddedWidget, we need the rule of the real widget
2495#if QT_CONFIG(combobox)
2496 if (qobject_cast<const QComboBox *>(w->parentWidget()))
2497 return w->parentWidget();
2498#endif
2499#if QT_CONFIG(spinbox)
2500 if (qobject_cast<const QAbstractSpinBox *>(w->parentWidget()))
2501 return w->parentWidget();
2502#endif
2503 }
2504#endif // QT_CONFIG(lineedit)
2505
2506#if QT_CONFIG(scrollarea)
2507 if (const QAbstractScrollArea *sa = qobject_cast<const QAbstractScrollArea *>(w->parentWidget())) {
2508 if (sa->viewport() == w)
2509 return w->parentWidget();
2510 }
2511#endif
2512
2513 return w;
2514}
2515
2516/** \internal
2517 returns \c true if the widget can NOT be styled directly
2518 */
2519static bool unstylable(const QWidget *w)
2520{
2521 if (!w->styleSheet().isEmpty())
2522 return false;
2523
2524 if (containerWidget(w) != w)
2525 return true;
2526
2527#ifndef QT_NO_FRAME
2528 // detect QComboBoxPrivateContainer
2529 else if (qobject_cast<const QFrame *>(w)) {
2530 if (0
2531#if QT_CONFIG(combobox)
2532 || qobject_cast<const QComboBox *>(w->parentWidget())
2533#endif
2534 )
2535 return true;
2536 }
2537#endif
2538
2539#if QT_CONFIG(tabbar)
2540 if (w->metaObject() == &QWidget::staticMetaObject
2541 && qobject_cast<const QTabBar*>(w->parentWidget()))
2542 return true; // The moving tab of a QTabBar
2543#endif
2544
2545 return false;
2546}
2547
2548static quint64 extendedPseudoClass(const QWidget *w)
2549{
2550 quint64 pc = w->isWindow() ? quint64(PseudoClass_Window) : 0;
2551#if QT_CONFIG(abstractslider)
2552 if (const QAbstractSlider *slider = qobject_cast<const QAbstractSlider *>(w)) {
2553 pc |= ((slider->orientation() == Qt::Vertical) ? PseudoClass_Vertical : PseudoClass_Horizontal);
2554 } else
2555#endif
2556#if QT_CONFIG(combobox)
2557 if (const QComboBox *combo = qobject_cast<const QComboBox *>(w)) {
2558 if (combo->isEditable())
2559 pc |= (combo->isEditable() ? PseudoClass_Editable : PseudoClass_ReadOnly);
2560 } else
2561#endif
2562#if QT_CONFIG(lineedit)
2563 if (const QLineEdit *edit = qobject_cast<const QLineEdit *>(w)) {
2564 pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
2565 } else
2566#endif
2567#if QT_CONFIG(textedit)
2568 if (const QTextEdit *edit = qobject_cast<const QTextEdit *>(w)) {
2569 pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
2570 } else
2571 if (const QPlainTextEdit *edit = qobject_cast<const QPlainTextEdit *>(w)) {
2572 pc |= (edit->isReadOnly() ? PseudoClass_ReadOnly : PseudoClass_Editable);
2573 } else
2574#endif
2575 {}
2576 return pc;
2577}
2578
2579// sets up the geometry of the widget. We set a dynamic property when
2580// we modify the min/max size of the widget. The min/max size is restored
2581// to their original value when a new stylesheet that does not contain
2582// the CSS properties is set and when the widget has this dynamic property set.
2583// This way we don't trample on users who had setup a min/max size in code and
2584// don't use stylesheets at all.
2585void QStyleSheetStyle::setGeometry(QWidget *w)
2586{
2587 QRenderRule rule = renderRule(w, PseudoElement_None, PseudoClass_Enabled | extendedPseudoClass(w));
2588 const QStyleSheetGeometryData *geo = rule.geometry();
2589 if (w->property("_q_stylesheet_minw").toBool()
2590 && ((!rule.hasGeometry() || geo->minWidth == -1))) {
2591 w->setMinimumWidth(0);
2592 w->setProperty("_q_stylesheet_minw", QVariant());
2593 }
2594 if (w->property("_q_stylesheet_minh").toBool()
2595 && ((!rule.hasGeometry() || geo->minHeight == -1))) {
2596 w->setMinimumHeight(0);
2597 w->setProperty("_q_stylesheet_minh", QVariant());
2598 }
2599 if (w->property("_q_stylesheet_maxw").toBool()
2600 && ((!rule.hasGeometry() || geo->maxWidth == -1))) {
2601 w->setMaximumWidth(QWIDGETSIZE_MAX);
2602 w->setProperty("_q_stylesheet_maxw", QVariant());
2603 }
2604 if (w->property("_q_stylesheet_maxh").toBool()
2605 && ((!rule.hasGeometry() || geo->maxHeight == -1))) {
2606 w->setMaximumHeight(QWIDGETSIZE_MAX);
2607 w->setProperty("_q_stylesheet_maxh", QVariant());
2608 }
2609
2610
2611 if (rule.hasGeometry()) {
2612 if (geo->minWidth != -1) {
2613 w->setProperty("_q_stylesheet_minw", true);
2614 w->setMinimumWidth(rule.boxSize(QSize(qMax(geo->width, geo->minWidth), 0)).width());
2615 }
2616 if (geo->minHeight != -1) {
2617 w->setProperty("_q_stylesheet_minh", true);
2618 w->setMinimumHeight(rule.boxSize(QSize(0, qMax(geo->height, geo->minHeight))).height());
2619 }
2620 if (geo->maxWidth != -1) {
2621 w->setProperty("_q_stylesheet_maxw", true);
2622 w->setMaximumWidth(rule.boxSize(QSize(qMin(geo->width == -1 ? QWIDGETSIZE_MAX : geo->width,
2623 geo->maxWidth == -1 ? QWIDGETSIZE_MAX : geo->maxWidth), 0)).width());
2624 }
2625 if (geo->maxHeight != -1) {
2626 w->setProperty("_q_stylesheet_maxh", true);
2627 w->setMaximumHeight(rule.boxSize(QSize(0, qMin(geo->height == -1 ? QWIDGETSIZE_MAX : geo->height,
2628 geo->maxHeight == -1 ? QWIDGETSIZE_MAX : geo->maxHeight))).height());
2629 }
2630 }
2631}
2632
2633void QStyleSheetStyle::setProperties(QWidget *w)
2634{
2635 // The final occurrence of each property is authoritative.
2636 // Set value for each property in the order of property final occurrence
2637 // since properties interact.
2638
2639 const QList<Declaration> decls = declarations(styleRules(w), {});
2640 QList<int> finals; // indices in reverse order of each property's final occurrence
2641
2642 {
2643 // scan decls for final occurrence of each "qproperty"
2644 QDuplicateTracker<QString> propertySet(decls.size());
2645 for (int i = decls.size() - 1; i >= 0; --i) {
2646 const QString property = decls.at(i).d->property;
2647 if (!property.startsWith("qproperty-"_L1, Qt::CaseInsensitive))
2648 continue;
2649 if (!propertySet.hasSeen(property))
2650 finals.append(i);
2651 }
2652 }
2653
2654 for (int i = finals.size() - 1; i >= 0; --i) {
2655 const Declaration &decl = decls.at(finals[i]);
2656 QStringView property = decl.d->property;
2657 property = property.mid(10); // strip "qproperty-"
2658 const auto propertyL1 = property.toLatin1();
2659
2660 const QMetaObject *metaObject = w->metaObject();
2661 int index = metaObject->indexOfProperty(propertyL1);
2662 if (Q_UNLIKELY(index == -1)) {
2663 qWarning() << w << " does not have a property named " << property;
2664 continue;
2665 }
2666 const QMetaProperty metaProperty = metaObject->property(index);
2667 if (Q_UNLIKELY(!metaProperty.isWritable() || !metaProperty.isDesignable())) {
2668 qWarning() << w << " cannot design property named " << property;
2669 continue;
2670 }
2671
2672 QVariant v;
2673 const QVariant value = w->property(propertyL1);
2674 switch (value.userType()) {
2675 case QMetaType::QIcon: v = decl.iconValue(); break;
2676 case QMetaType::QImage: v = QImage(decl.uriValue()); break;
2677 case QMetaType::QPixmap: v = QPixmap(decl.uriValue()); break;
2678 case QMetaType::QRect: v = decl.rectValue(); break;
2679 case QMetaType::QSize: v = decl.sizeValue(); break;
2680 case QMetaType::QColor: v = decl.colorValue(); break;
2681 case QMetaType::QBrush: v = decl.brushValue(); break;
2682#ifndef QT_NO_SHORTCUT
2683 case QMetaType::QKeySequence: v = QKeySequence(decl.d->values.at(0).variant.toString()); break;
2684#endif
2685 default: v = decl.d->values.at(0).variant; break;
2686 }
2687
2688 if (propertyL1 == QByteArrayView("styleSheet") && value == v)
2689 continue;
2690
2691 w->setProperty(propertyL1, v);
2692 }
2693}
2694
2695void QStyleSheetStyle::setPalette(QWidget *w)
2696{
2697 struct RuleRoleMap {
2698 int state;
2699 QPalette::ColorGroup group;
2700 } map[3] = {
2701 { int(PseudoClass_Active | PseudoClass_Enabled), QPalette::Active },
2702 { PseudoClass_Disabled, QPalette::Disabled },
2703 { PseudoClass_Enabled, QPalette::Inactive }
2704 };
2705
2706 const bool useStyleSheetPropagationInWidgetStyles =
2707 QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
2708
2709 QPalette p;
2710 if (!useStyleSheetPropagationInWidgetStyles)
2711 p = w->palette();
2712
2713 QWidget *ew = embeddedWidget(w);
2714
2715 for (int i = 0; i < 3; i++) {
2716 QRenderRule rule = renderRule(w, PseudoElement_None, map[i].state | extendedPseudoClass(w));
2717 if (i == 0) {
2718 if (!w->property("_q_styleSheetWidgetFont").isValid()) {
2719 saveWidgetFont(w, w->d_func()->localFont());
2720 }
2721 updateStyleSheetFont(w);
2722 if (ew != w)
2723 updateStyleSheetFont(ew);
2724 }
2725
2726 rule.configurePalette(&p, map[i].group, ew, ew != w);
2727 }
2728
2729 if (!useStyleSheetPropagationInWidgetStyles || p.resolveMask() != 0) {
2730 QPalette wp = w->palette();
2731 styleSheetCaches->customPaletteWidgets.insert(w, {wp, p.resolveMask()});
2732
2733 if (useStyleSheetPropagationInWidgetStyles) {
2734 p = p.resolve(wp);
2735 p.setResolveMask(p.resolveMask() | wp.resolveMask());
2736 }
2737
2738 w->setPalette(p);
2739 if (ew != w)
2740 ew->setPalette(p);
2741 }
2742}
2743
2744void QStyleSheetStyle::unsetPalette(QWidget *w)
2745{
2746 const bool useStyleSheetPropagationInWidgetStyles =
2747 QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
2748
2749 const auto it = styleSheetCaches->customPaletteWidgets.find(w);
2750 if (it != styleSheetCaches->customPaletteWidgets.end()) {
2751 auto customizedPalette = std::move(*it);
2752 styleSheetCaches->customPaletteWidgets.erase(it);
2753
2754 QPalette original;
2755 if (useStyleSheetPropagationInWidgetStyles)
2756 original = std::move(customizedPalette).reverted(w->palette());
2757 else
2758 original = customizedPalette.oldWidgetValue;
2759
2760 w->setPalette(original);
2761 QWidget *ew = embeddedWidget(w);
2762 if (ew != w)
2763 ew->setPalette(original);
2764 }
2765
2766 QWidget *ew = embeddedWidget(w);
2767 if (useStyleSheetPropagationInWidgetStyles) {
2768 unsetStyleSheetFont(w);
2769 if (ew != w)
2770 unsetStyleSheetFont(ew);
2771 } else {
2772 QVariant oldFont = w->property("_q_styleSheetWidgetFont");
2773 if (oldFont.isValid()) {
2774 const QFont f = qvariant_cast<QFont>(oldFont);
2775 w->setFont(f);
2776 if (ew != w)
2777 ew->setFont(f);
2778 }
2779 }
2780
2781 if (styleSheetCaches->autoFillDisabledWidgets.contains(w)) {
2782 embeddedWidget(w)->setAutoFillBackground(true);
2783 styleSheetCaches->autoFillDisabledWidgets.remove(w);
2784 }
2785}
2786
2787void QStyleSheetStyle::unsetStyleSheetFont(QWidget *w) const
2788{
2789 const auto it = styleSheetCaches->customFontWidgets.find(w);
2790 if (it != styleSheetCaches->customFontWidgets.end()) {
2791 auto customizedFont = std::move(*it);
2792 styleSheetCaches->customFontWidgets.erase(it);
2793 w->setFont(std::move(customizedFont).reverted(w->font()));
2794 }
2795}
2796
2797static void updateObjects(const QList<const QObject *>& objects)
2798{
2799 if (!styleSheetCaches->styleRulesCache.isEmpty() || !styleSheetCaches->hasStyleRuleCache.isEmpty() || !styleSheetCaches->renderRulesCache.isEmpty()) {
2800 for (const QObject *object : objects) {
2801 styleSheetCaches->styleRulesCache.remove(object);
2802 styleSheetCaches->hasStyleRuleCache.remove(object);
2803 styleSheetCaches->renderRulesCache.remove(object);
2804 }
2805 }
2806
2807 QEvent event(QEvent::StyleChange);
2808 for (const QObject *object : objects) {
2809 if (auto widget = qobject_cast<QWidget*>(const_cast<QObject*>(object))) {
2810 widget->style()->polish(widget);
2811 QCoreApplication::sendEvent(widget, &event);
2812 QList<const QObject *> children;
2813 children.reserve(widget->children().size() + 1);
2814 for (auto child: std::as_const(widget->children()))
2815 children.append(child);
2816 updateObjects(children);
2817 }
2818 }
2819}
2820
2821/////////////////////////////////////////////////////////////////////////////////////////
2822// The stylesheet style
2823int QStyleSheetStyle::numinstances = 0;
2824
2825QStyleSheetStyle::QStyleSheetStyle(QStyle *base)
2826 : QWindowsStyle(*new QStyleSheetStylePrivate), base(base), refcount(1)
2827{
2828 ++numinstances;
2829 if (numinstances == 1) {
2830 styleSheetCaches = new QStyleSheetStyleCaches;
2831 }
2832}
2833
2834QStyleSheetStyle::~QStyleSheetStyle()
2835{
2836 --numinstances;
2837 if (numinstances == 0) {
2838 delete styleSheetCaches;
2839 }
2840}
2841QStyle *QStyleSheetStyle::baseStyle() const
2842{
2843 if (base)
2844 return base;
2845 if (QStyleSheetStyle *me = qt_styleSheet(QApplication::style()))
2846 return me->base;
2847 return QApplication::style();
2848}
2849
2850void QStyleSheetStyleCaches::objectDestroyed(QObject *o)
2851{
2852 styleRulesCache.remove(o);
2853 hasStyleRuleCache.remove(o);
2854 renderRulesCache.remove(o);
2855 customPaletteWidgets.remove((const QWidget *)o);
2856 customFontWidgets.remove(static_cast<QWidget *>(o));
2857 styleSheetCache.remove(o);
2858 autoFillDisabledWidgets.remove((const QWidget *)o);
2859}
2860
2861void QStyleSheetStyleCaches::styleDestroyed(QObject *o)
2862{
2863 styleSheetCache.remove(o);
2864}
2865
2866/*!
2867 * Make sure that the cache will be clean by connecting destroyed if needed.
2868 * return false if the widget is not stylable;
2869 */
2870bool QStyleSheetStyle::initWidget(const QWidget *w) const
2871{
2872 if (!w)
2873 return false;
2874 if (w->testAttribute(Qt::WA_StyleSheet))
2875 return true;
2876 if (unstylable(w))
2877 return false;
2878 const_cast<QWidget *>(w)->setAttribute(Qt::WA_StyleSheet, true);
2879
2880 connect(w, &QObject::destroyed,
2881 styleSheetCaches, &QStyleSheetStyleCaches::objectDestroyed,
2882 Qt::UniqueConnection);
2883 return true;
2884}
2885
2886void QStyleSheetStyle::polish(QWidget *w)
2887{
2888 baseStyle()->polish(w);
2889 RECURSION_GUARD(return)
2890
2891 if (!initWidget(w))
2892 return;
2893
2894 if (styleSheetCaches->styleRulesCache.contains(w)) {
2895 // the widget accessed its style pointer before polish (or repolish)
2896 // (example: the QAbstractSpinBox constructor ask for the stylehint)
2897 styleSheetCaches->styleRulesCache.remove(w);
2898 styleSheetCaches->hasStyleRuleCache.remove(w);
2899 styleSheetCaches->renderRulesCache.remove(w);
2900 styleSheetCaches->styleSheetCache.remove(w);
2901 }
2902 setGeometry(w);
2903 setProperties(w);
2904 unsetPalette(w);
2905 setPalette(w);
2906
2907 //set the WA_Hover attribute if one of the selector depends of the hover state
2908 const QList<StyleRule> rules = styleRules(w);
2909 for (const auto &rule : rules) {
2910 const Selector &selector = rule.selectors.at(0);
2911 quint64 negated = 0;
2912 quint64 cssClass = selector.pseudoClass(&negated);
2913 if ( cssClass & PseudoClass_Hover || negated & PseudoClass_Hover) {
2914 w->setAttribute(Qt::WA_Hover);
2915 embeddedWidget(w)->setAttribute(Qt::WA_Hover);
2916 embeddedWidget(w)->setMouseTracking(true);
2917 }
2918 }
2919
2920
2921#if QT_CONFIG(scrollarea)
2922 if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
2923 QRenderRule rule = renderRule(sa, PseudoElement_None, PseudoClass_Enabled);
2924 if ((rule.hasBorder() && rule.border()->hasBorderImage())
2925 || (rule.hasBackground() && !rule.background()->pixmap.isNull())) {
2926 connect(sa->horizontalScrollBar(), &QScrollBar::valueChanged,
2927 sa, QOverload<>::of(&QAbstractScrollArea::update), Qt::UniqueConnection);
2928 connect(sa->verticalScrollBar(), &QScrollBar::valueChanged,
2929 sa, QOverload<>::of(&QAbstractScrollArea::update), Qt::UniqueConnection);
2930 }
2931 }
2932#endif
2933
2934 QRenderRule rule = renderRule(w, PseudoElement_None, PseudoClass_Any);
2935
2936 w->setAttribute(Qt::WA_StyleSheetTarget, rule.hasModification());
2937
2938 if (rule.hasDrawable() || rule.hasBox()) {
2939 if (w->metaObject() == &QWidget::staticMetaObject
2940#if QT_CONFIG(itemviews)
2941 || qobject_cast<QHeaderView *>(w)
2942#endif
2943#if QT_CONFIG(tabbar)
2944 || qobject_cast<QTabBar *>(w)
2945#endif
2946#ifndef QT_NO_FRAME
2947 || qobject_cast<QFrame *>(w)
2948#endif
2949#if QT_CONFIG(mainwindow)
2950 || qobject_cast<QMainWindow *>(w)
2951#endif
2952#if QT_CONFIG(mdiarea)
2953 || qobject_cast<QMdiSubWindow *>(w)
2954#endif
2955#if QT_CONFIG(menubar)
2956 || qobject_cast<QMenuBar *>(w)
2957#endif
2958#if QT_CONFIG(dialog)
2959 || qobject_cast<QDialog *>(w)
2960#endif
2961 ) {
2962 w->setAttribute(Qt::WA_StyledBackground, true);
2963 }
2964 QWidget *ew = embeddedWidget(w);
2965 if (ew->autoFillBackground()) {
2966 ew->setAutoFillBackground(false);
2967 styleSheetCaches->autoFillDisabledWidgets.insert(w);
2968 if (ew != w) { //eg. viewport of a scrollarea
2969 //(in order to draw the background anyway in case we don't.)
2970 ew->setAttribute(Qt::WA_StyledBackground, true);
2971 }
2972 }
2973 if (!rule.hasBackground() || rule.background()->isTransparent() || rule.hasBox()
2974 || (!rule.hasNativeBorder() && !rule.border()->isOpaque()))
2975 w->setAttribute(Qt::WA_OpaquePaintEvent, false);
2976 if (rule.hasBox() || !rule.hasNativeBorder()
2977#if QT_CONFIG(pushbutton)
2978 || (qobject_cast<QPushButton *>(w))
2979#endif
2980 )
2981 w->setAttribute(Qt::WA_MacShowFocusRect, false);
2982 }
2983}
2984
2985void QStyleSheetStyle::polish(QApplication *app)
2986{
2987 baseStyle()->polish(app);
2988}
2989
2990void QStyleSheetStyle::polish(QPalette &pal)
2991{
2992 baseStyle()->polish(pal);
2993}
2994
2995void QStyleSheetStyle::repolish(QWidget *w)
2996{
2997 QList<const QObject *> children;
2998 children.reserve(w->children().size() + 1);
2999 for (auto child: std::as_const(w->children()))
3000 children.append(child);
3001 children.append(w);
3002 styleSheetCaches->styleSheetCache.remove(w);
3003 updateObjects(children);
3004}
3005
3006void QStyleSheetStyle::repolish(QApplication *app)
3007{
3008 Q_UNUSED(app);
3009 const QList<const QObject*> allObjects = styleSheetCaches->styleRulesCache.keys();
3010 styleSheetCaches->styleSheetCache.remove(qApp);
3011 styleSheetCaches->styleRulesCache.clear();
3012 styleSheetCaches->hasStyleRuleCache.clear();
3013 styleSheetCaches->renderRulesCache.clear();
3014 updateObjects(allObjects);
3015}
3016
3017void QStyleSheetStyle::unpolish(QWidget *w)
3018{
3019 if (!w || !w->testAttribute(Qt::WA_StyleSheet)) {
3020 baseStyle()->unpolish(w);
3021 return;
3022 }
3023
3024 styleSheetCaches->styleRulesCache.remove(w);
3025 styleSheetCaches->hasStyleRuleCache.remove(w);
3026 styleSheetCaches->renderRulesCache.remove(w);
3027 styleSheetCaches->styleSheetCache.remove(w);
3028 unsetPalette(w);
3029 setGeometry(w);
3030 w->setAttribute(Qt::WA_StyleSheetTarget, false);
3031 w->setAttribute(Qt::WA_StyleSheet, false);
3032 w->disconnect(this);
3033#if QT_CONFIG(scrollarea)
3034 if (QAbstractScrollArea *sa = qobject_cast<QAbstractScrollArea *>(w)) {
3035 disconnect(sa->horizontalScrollBar(), &QScrollBar::valueChanged,
3036 sa, QOverload<>::of(&QAbstractScrollArea::update));
3037 disconnect(sa->verticalScrollBar(), &QScrollBar::valueChanged,
3038 sa, QOverload<>::of(&QAbstractScrollArea::update));
3039 }
3040#endif
3041 baseStyle()->unpolish(w);
3042}
3043
3044void QStyleSheetStyle::unpolish(QApplication *app)
3045{
3046 baseStyle()->unpolish(app);
3047 RECURSION_GUARD(return)
3048 styleSheetCaches->styleRulesCache.clear();
3049 styleSheetCaches->hasStyleRuleCache.clear();
3050 styleSheetCaches->renderRulesCache.clear();
3051 styleSheetCaches->styleSheetCache.remove(qApp);
3052}
3053
3054void QStyleSheetStyle::drawComplexControl(ComplexControl cc, const QStyleOptionComplex *opt, QPainter *p,
3055 const QWidget *w) const
3056{
3057 RECURSION_GUARD(baseStyle()->drawComplexControl(cc, opt, p, w); return)
3058
3059 QRenderRule rule = renderRule(w, opt);
3060
3061 switch (cc) {
3062 case CC_ComboBox:
3063 if (const QStyleOptionComboBox *cmb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
3064 QStyleOptionComboBox cmbOpt(*cmb);
3065 cmbOpt.rect = rule.borderRect(opt->rect);
3066 if (rule.hasNativeBorder()) {
3067 rule.drawBackgroundImage(p, cmbOpt.rect);
3068 rule.configurePalette(&cmbOpt.palette, QPalette::ButtonText, QPalette::Button);
3069 bool customDropDown = (opt->subControls & QStyle::SC_ComboBoxArrow)
3070 && (hasStyleRule(w, PseudoElement_ComboBoxDropDown) || hasStyleRule(w, PseudoElement_ComboBoxArrow));
3071 if (customDropDown)
3072 cmbOpt.subControls &= ~QStyle::SC_ComboBoxArrow;
3073 if (rule.baseStyleCanDraw()) {
3074 baseStyle()->drawComplexControl(cc, &cmbOpt, p, w);
3075 } else {
3076 QWindowsStyle::drawComplexControl(cc, &cmbOpt, p, w);
3077 }
3078 if (!customDropDown)
3079 return;
3080 } else {
3081 rule.drawRule(p, opt->rect);
3082 }
3083
3084 if (opt->subControls & QStyle::SC_ComboBoxArrow) {
3085 QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
3086 if (subRule.hasDrawable()) {
3087 QRect r = subControlRect(CC_ComboBox, opt, SC_ComboBoxArrow, w);
3088 subRule.drawRule(p, r);
3089 QRenderRule subRule2 = renderRule(w, opt, PseudoElement_ComboBoxArrow);
3090 r = positionRect(w, subRule, subRule2, PseudoElement_ComboBoxArrow, r, opt->direction);
3091 subRule2.drawRule(p, r);
3092 } else {
3093 rule.configurePalette(&cmbOpt.palette, QPalette::ButtonText, QPalette::Button);
3094 cmbOpt.subControls = QStyle::SC_ComboBoxArrow;
3095 QWindowsStyle::drawComplexControl(cc, &cmbOpt, p, w);
3096 }
3097 }
3098
3099 return;
3100 }
3101 break;
3102
3103#if QT_CONFIG(spinbox)
3104 case CC_SpinBox:
3105 if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
3106 QStyleOptionSpinBox spinOpt(*spin);
3107 rule.configurePalette(&spinOpt.palette, QPalette::ButtonText, QPalette::Button);
3108 rule.configurePalette(&spinOpt.palette, QPalette::Text, QPalette::Base);
3109 spinOpt.rect = rule.borderRect(opt->rect);
3110 bool customUp = true, customDown = true;
3111 QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
3112 QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
3113 bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition();
3114 bool downRuleMatch = downRule.hasGeometry() || downRule.hasPosition();
3115 if (rule.hasNativeBorder() && !upRuleMatch && !downRuleMatch) {
3116 rule.drawBackgroundImage(p, spinOpt.rect);
3117 customUp = (opt->subControls & QStyle::SC_SpinBoxUp)
3118 && (hasStyleRule(w, PseudoElement_SpinBoxUpButton) || hasStyleRule(w, PseudoElement_UpArrow));
3119 if (customUp)
3120 spinOpt.subControls &= ~QStyle::SC_SpinBoxUp;
3121 customDown = (opt->subControls & QStyle::SC_SpinBoxDown)
3122 && (hasStyleRule(w, PseudoElement_SpinBoxDownButton) || hasStyleRule(w, PseudoElement_DownArrow));
3123 if (customDown)
3124 spinOpt.subControls &= ~QStyle::SC_SpinBoxDown;
3125 if (rule.baseStyleCanDraw()) {
3126 baseStyle()->drawComplexControl(cc, &spinOpt, p, w);
3127 } else {
3128 QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
3129 }
3130 if (!customUp && !customDown)
3131 return;
3132 } else {
3133 rule.drawRule(p, opt->rect);
3134 }
3135
3136 if ((opt->subControls & QStyle::SC_SpinBoxUp) && customUp) {
3137 QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
3138 if (subRule.hasDrawable()) {
3139 QRect r = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w);
3140 subRule.drawRule(p, r);
3141 QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SpinBoxUpArrow);
3142 r = positionRect(w, subRule, subRule2, PseudoElement_SpinBoxUpArrow, r, opt->direction);
3143 subRule2.drawRule(p, r);
3144 } else {
3145 spinOpt.subControls = QStyle::SC_SpinBoxUp;
3146 QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
3147 }
3148 }
3149
3150 if ((opt->subControls & QStyle::SC_SpinBoxDown) && customDown) {
3151 QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
3152 if (subRule.hasDrawable()) {
3153 QRect r = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w);
3154 subRule.drawRule(p, r);
3155 QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SpinBoxDownArrow);
3156 r = positionRect(w, subRule, subRule2, PseudoElement_SpinBoxDownArrow, r, opt->direction);
3157 subRule2.drawRule(p, r);
3158 } else {
3159 spinOpt.subControls = QStyle::SC_SpinBoxDown;
3160 QWindowsStyle::drawComplexControl(cc, &spinOpt, p, w);
3161 }
3162 }
3163 return;
3164 }
3165 break;
3166#endif // QT_CONFIG(spinbox)
3167
3168 case CC_GroupBox:
3169 if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
3170
3171 QRect labelRect, checkBoxRect, titleRect, frameRect;
3172 bool hasTitle = (gb->subControls & QStyle::SC_GroupBoxCheckBox) || !gb->text.isEmpty();
3173
3174 if (!rule.hasDrawable() && (!hasTitle || !hasStyleRule(w, PseudoElement_GroupBoxTitle))
3175 && !hasStyleRule(w, PseudoElement_Indicator) && !rule.hasBox() && !rule.hasFont && !rule.hasPalette()) {
3176 // let the native style draw the combobox if there is no style for it.
3177 break;
3178 }
3179 rule.drawBackground(p, opt->rect);
3180
3181 QRenderRule titleRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
3182 bool clipSet = false;
3183
3184 if (hasTitle) {
3185 labelRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w);
3186 //Some native style (such as mac) may return a too small rectangle (because they use smaller fonts), so we may need to expand it a little bit.
3187 labelRect.setSize(labelRect.size().expandedTo(ParentStyle::subControlRect(CC_GroupBox, opt, SC_GroupBoxLabel, w).size()));
3188 if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
3189 checkBoxRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxCheckBox, w);
3190 titleRect = titleRule.boxRect(checkBoxRect.united(labelRect));
3191 } else {
3192 titleRect = titleRule.boxRect(labelRect);
3193 }
3194 if (!titleRule.hasBackground() || !titleRule.background()->isTransparent()) {
3195 clipSet = true;
3196 p->save();
3197 p->setClipRegion(QRegion(opt->rect) - titleRect);
3198 }
3199 }
3200
3201 frameRect = subControlRect(CC_GroupBox, opt, SC_GroupBoxFrame, w);
3202 QStyleOptionFrame frame;
3203 frame.QStyleOption::operator=(*gb);
3204 frame.features = gb->features;
3205 frame.lineWidth = gb->lineWidth;
3206 frame.midLineWidth = gb->midLineWidth;
3207 frame.rect = frameRect;
3208 drawPrimitive(PE_FrameGroupBox, &frame, p, w);
3209
3210 if (clipSet)
3211 p->restore();
3212
3213 // draw background and frame of the title
3214 if (hasTitle)
3215 titleRule.drawRule(p, titleRect);
3216
3217 // draw the indicator
3218 if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
3219 QStyleOptionButton box;
3220 box.QStyleOption::operator=(*gb);
3221 box.rect = checkBoxRect;
3222 drawPrimitive(PE_IndicatorCheckBox, &box, p, w);
3223 }
3224
3225 // draw the text
3226 if (!gb->text.isEmpty()) {
3227 int alignment = int(Qt::AlignCenter | Qt::TextShowMnemonic);
3228 if (!styleHint(QStyle::SH_UnderlineShortcut, opt, w)) {
3229 alignment |= Qt::TextHideMnemonic;
3230 }
3231
3232 QPalette pal = gb->palette;
3233 if (gb->textColor.isValid())
3234 pal.setColor(QPalette::WindowText, gb->textColor);
3235 titleRule.configurePalette(&pal, QPalette::WindowText, QPalette::Window);
3236 drawItemText(p, labelRect, alignment, pal, gb->state & State_Enabled,
3237 gb->text, QPalette::WindowText);
3238
3239 if (gb->state & State_HasFocus) {
3240 QStyleOptionFocusRect fropt;
3241 fropt.QStyleOption::operator=(*gb);
3242 fropt.rect = labelRect;
3243 drawPrimitive(PE_FrameFocusRect, &fropt, p, w);
3244 }
3245 }
3246
3247 return;
3248 }
3249 break;
3250
3251 case CC_ToolButton:
3252#if QT_CONFIG(toolbutton)
3253 if (const QStyleOptionToolButton *tool = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
3254 QStyleOptionToolButton toolOpt(*tool);
3255 rule.configurePalette(&toolOpt.palette, QPalette::ButtonText, QPalette::Button);
3256 toolOpt.font = rule.font.resolve(toolOpt.font);
3257 toolOpt.rect = rule.borderRect(opt->rect);
3258 const auto customArrowElement = [tool]{
3259 switch (tool->arrowType) {
3260 case Qt::DownArrow: return PseudoElement_DownArrow;
3261 case Qt::UpArrow: return PseudoElement_UpArrow;
3262 case Qt::LeftArrow: return PseudoElement_LeftArrow;
3263 case Qt::RightArrow: return PseudoElement_RightArrow;
3264 default: break;
3265 }
3266 return PseudoElement_None;
3267 };
3268 // if arrow/menu/indicators are requested, either draw them using the available rule,
3269 // or let the base style draw them; but not both
3270 const bool drawArrow = tool->features & QStyleOptionToolButton::Arrow;
3271 bool customArrow = drawArrow && hasStyleRule(w, customArrowElement());
3272 if (customArrow) {
3273 toolOpt.features &= ~QStyleOptionToolButton::Arrow;
3274 toolOpt.text = QString(); // we need to draw the arrow and the text ourselves
3275 }
3276 bool drawDropDown = tool->features & QStyleOptionToolButton::MenuButtonPopup;
3277 bool customDropDown = drawDropDown && hasStyleRule(w, PseudoElement_ToolButtonMenu);
3278 bool customDropDownArrow = false;
3279 bool drawMenuIndicator = tool->features & QStyleOptionToolButton::HasMenu;
3280 if (customDropDown) {
3281 toolOpt.subControls &= ~QStyle::SC_ToolButtonMenu;
3282 customDropDownArrow = hasStyleRule(w, PseudoElement_ToolButtonMenuArrow);
3283 if (customDropDownArrow)
3284 toolOpt.features &= ~(QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu);
3285 }
3286 const bool customMenuIndicator = (!drawDropDown && drawMenuIndicator)
3287 && hasStyleRule(w, PseudoElement_ToolButtonMenuIndicator);
3288 if (customMenuIndicator)
3289 toolOpt.features &= ~QStyleOptionToolButton::HasMenu;
3290
3291 if (rule.hasNativeBorder()) {
3292 if (tool->subControls & SC_ToolButton) {
3293 //in some case (eg. the button is "auto raised") the style doesn't draw the background
3294 //so we need to draw the background.
3295 // use the same condition as in QCommonStyle
3296 State bflags = tool->state & ~State_Sunken;
3297 if (bflags & State_AutoRaise && (!(bflags & State_MouseOver) || !(bflags & State_Enabled)))
3298 bflags &= ~State_Raised;
3299 if (tool->state & State_Sunken && tool->activeSubControls & SC_ToolButton)
3300 bflags |= State_Sunken;
3301 if (!(bflags & (State_Sunken | State_On | State_Raised)))
3302 rule.drawBackground(p, toolOpt.rect);
3303 }
3304
3305 QStyleOptionToolButton nativeToolOpt(toolOpt);
3306 // don't draw natively if we have a custom rule for menu indicators and/or buttons
3307 if (customMenuIndicator)
3308 nativeToolOpt.features &= ~(QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu);
3309 if (customDropDown || customDropDownArrow)
3310 nativeToolOpt.features &= ~(QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu | QStyleOptionToolButton::MenuButtonPopup);
3311 // Let base or windows style draw the button, which will include the menu-button
3312 if (rule.baseStyleCanDraw() && !(tool->features & QStyleOptionToolButton::Arrow))
3313 baseStyle()->drawComplexControl(cc, &nativeToolOpt, p, w);
3314 else
3315 QWindowsStyle::drawComplexControl(cc, &nativeToolOpt, p, w);
3316 // if we did draw natively, don't draw custom
3317 if (nativeToolOpt.features & (QStyleOptionToolButton::Menu | QStyleOptionToolButton::HasMenu))
3318 drawMenuIndicator = false;
3319 if (nativeToolOpt.features & QStyleOptionToolButton::MenuButtonPopup && !customDropDownArrow)
3320 drawDropDown = false;
3321 } else {
3322 rule.drawRule(p, opt->rect);
3323 toolOpt.rect = rule.contentsRect(opt->rect);
3324 if (rule.hasFont)
3325 toolOpt.font = rule.font.resolve(toolOpt.font);
3326 drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
3327 }
3328
3329 const QRect cr = toolOpt.rect;
3330 // Draw DropDownButton unless drawn before
3331 if (drawDropDown) {
3332 if (opt->subControls & QStyle::SC_ToolButtonMenu) {
3333 QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
3334 QRect menuButtonRect = subControlRect(CC_ToolButton, opt, QStyle::SC_ToolButtonMenu, w);
3335 if (subRule.hasDrawable()) {
3336 subRule.drawRule(p, menuButtonRect);
3337 } else {
3338 toolOpt.rect = menuButtonRect;
3339 baseStyle()->drawPrimitive(PE_IndicatorButtonDropDown, &toolOpt, p, w);
3340 }
3341
3342 if (customDropDownArrow || drawMenuIndicator) {
3343 QRenderRule arrowRule = renderRule(w, opt, PseudoElement_ToolButtonMenuArrow);
3344 QRect arrowRect = arrowRule.hasGeometry()
3345 ? positionRect(w, arrowRule, PseudoElement_ToolButtonMenuArrow, menuButtonRect, toolOpt.direction)
3346 : arrowRule.contentsRect(menuButtonRect);
3347 if (arrowRule.hasDrawable()) {
3348 arrowRule.drawRule(p, arrowRect);
3349 } else {
3350 toolOpt.rect = arrowRect;
3351 baseStyle()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &toolOpt, p, w);
3352 }
3353 }
3354 }
3355 } else if (drawMenuIndicator) {
3356 QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenuIndicator);
3357
3358 // content padding does not impact the indicator, so use the original rect to
3359 // calculate position of the sub element within the toplevel rule
3360 QRect r = positionRect(w, rule, subRule, PseudoElement_ToolButtonMenuIndicator, opt->rect, toolOpt.direction);
3361 if (subRule.hasDrawable()) {
3362 subRule.drawRule(p, r);
3363 } else {
3364 toolOpt.rect = r;
3365 baseStyle()->drawPrimitive(QStyle::PE_IndicatorArrowDown, &toolOpt, p, w);
3366 }
3367 }
3368 toolOpt.rect = cr;
3369
3370 // If we don't have a custom arrow, then the arrow will have been rendered
3371 // already by the base style when drawing the label.
3372 if (customArrow) {
3373 const auto arrowElement = customArrowElement();
3374 QRenderRule subRule = renderRule(w, opt, arrowElement);
3375 QRect arrowRect = subRule.hasGeometry() ? positionRect(w, subRule, arrowElement, toolOpt.rect, toolOpt.direction)
3376 : subRule.contentsRect(toolOpt.rect);
3377
3378 switch (toolOpt.toolButtonStyle) {
3379 case Qt::ToolButtonIconOnly:
3380 break;
3381 case Qt::ToolButtonTextOnly:
3382 case Qt::ToolButtonTextBesideIcon:
3383 case Qt::ToolButtonTextUnderIcon: {
3384 // The base style needs to lay out the contents and will render the styled
3385 // arrow icons, unless the geometry is defined in the style sheet.
3386 toolOpt.text = tool->text;
3387 if (!subRule.hasGeometry())
3388 toolOpt.features |= QStyleOptionToolButton::Arrow;
3389 drawControl(CE_ToolButtonLabel, &toolOpt, p, w);
3390 if (!subRule.hasGeometry())
3391 return;
3392 break;
3393 }
3394 case Qt::ToolButtonFollowStyle:
3395 // QToolButton handles this, so must never happen
3396 Q_ASSERT(false);
3397 break;
3398 }
3399 subRule.drawRule(p, arrowRect);
3400 }
3401 return;
3402 }
3403#endif // QT_CONFIG(toolbutton)
3404 break;
3405
3406#if QT_CONFIG(scrollbar)
3407 case CC_ScrollBar:
3408 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3409 if (!rule.hasDrawable()) {
3410 QStyleOptionSlider sbOpt(*sb);
3411 sbOpt.rect = rule.borderRect(opt->rect);
3412 rule.drawBackgroundImage(p, opt->rect);
3413 baseStyle()->drawComplexControl(cc, &sbOpt, p, w);
3414 } else {
3415 rule.drawRule(p, opt->rect);
3416 QWindowsStyle::drawComplexControl(cc, opt, p, w);
3417 }
3418 return;
3419 }
3420 break;
3421#endif // QT_CONFIG(scrollbar)
3422
3423#if QT_CONFIG(slider)
3424 case CC_Slider:
3425 if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
3426 rule.drawRule(p, opt->rect);
3427
3428 QRenderRule grooveSubRule = renderRule(w, opt, PseudoElement_SliderGroove);
3429 QRenderRule handleSubRule = renderRule(w, opt, PseudoElement_SliderHandle);
3430 if (!grooveSubRule.hasDrawable()) {
3431 QStyleOptionSlider slOpt(*slider);
3432 bool handleHasRule = handleSubRule.hasDrawable();
3433 // If the style specifies a different handler rule, draw the groove without the handler.
3434 if (handleHasRule)
3435 slOpt.subControls &= ~SC_SliderHandle;
3436 baseStyle()->drawComplexControl(cc, &slOpt, p, w);
3437 if (!handleHasRule)
3438 return;
3439 }
3440
3441 QRect gr = subControlRect(cc, opt, SC_SliderGroove, w);
3442 if (slider->subControls & SC_SliderGroove)
3443 grooveSubRule.drawRule(p, gr);
3444
3445 if (slider->subControls & SC_SliderHandle) {
3446 QRect hr = subControlRect(cc, opt, SC_SliderHandle, w);
3447
3448 if (slider->subControls & SC_SliderGroove) {
3449 const bool isHor = slider->orientation == Qt::Horizontal;
3450 QRenderRule subRule1 = renderRule(w, opt, PseudoElement_SliderSubPage);
3451 if (subRule1.hasDrawable()) {
3452 QRect r(gr.topLeft(),
3453 isHor ? QPoint(hr.x() + hr.width() / 2, gr.y() + gr.height() - 1)
3454 : QPoint(gr.x() + gr.width() - 1, hr.y() + hr.height() / 2));
3455 subRule1.drawRule(p, r);
3456 }
3457 QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SliderAddPage);
3458 if (subRule2.hasDrawable()) {
3459 QRect r(isHor ? QPoint(hr.x() + hr.width() / 2 + 1, gr.y())
3460 : QPoint(gr.x(), hr.y() + hr.height() / 2 + 1),
3461 gr.bottomRight());
3462 subRule2.drawRule(p, r);
3463 }
3464 }
3465
3466 handleSubRule.drawRule(p, handleSubRule.boxRect(hr, Margin));
3467 }
3468
3469 if (slider->subControls & SC_SliderTickmarks) {
3470 // TODO...
3471 }
3472
3473 return;
3474 }
3475 break;
3476#endif // QT_CONFIG(slider)
3477
3478 case CC_MdiControls:
3479 if (hasStyleRule(w, PseudoElement_MdiCloseButton)
3480 || hasStyleRule(w, PseudoElement_MdiNormalButton)
3481 || hasStyleRule(w, PseudoElement_MdiMinButton)) {
3482 QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
3483 if (layout.isEmpty())
3484 layout = subControlLayout("mNX");
3485
3486 QStyleOptionComplex optCopy(*opt);
3487 optCopy.subControls = { };
3488 for (const QVariant &val : std::as_const(layout)) {
3489 int layoutButton = val.toInt();
3490 if (layoutButton < PseudoElement_MdiCloseButton
3491 || layoutButton > PseudoElement_MdiNormalButton)
3492 continue;
3493 QStyle::SubControl control = knownPseudoElements[layoutButton].subControl;
3494 if (!(opt->subControls & control))
3495 continue;
3496 QRenderRule subRule = renderRule(w, opt, layoutButton);
3497 if (subRule.hasDrawable()) {
3498 QRect rect = subRule.boxRect(subControlRect(CC_MdiControls, opt, control, w), Margin);
3499 subRule.drawRule(p, rect);
3500 QIcon icon = standardIcon(subControlIcon(layoutButton), opt);
3501 icon.paint(p, subRule.contentsRect(rect), Qt::AlignCenter);
3502 } else {
3503 optCopy.subControls |= control;
3504 }
3505 }
3506
3507 if (optCopy.subControls)
3508 baseStyle()->drawComplexControl(CC_MdiControls, &optCopy, p, w);
3509 return;
3510 }
3511 break;
3512
3513 case CC_TitleBar:
3514 if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
3515 QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
3516 if (!subRule.hasDrawable() && !subRule.hasBox() && !subRule.hasBorder())
3517 break;
3518 subRule.drawRule(p, opt->rect);
3519 QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
3520 const auto paintDeviceDpr = QStyleHelper::getDpr(p);
3521
3522 QRect ir;
3523 ir = layout[SC_TitleBarLabel];
3524 if (ir.isValid()) {
3525 if (subRule.hasPalette())
3526 p->setPen(subRule.palette()->foreground.color());
3527 p->fillRect(ir, Qt::white);
3528 p->drawText(ir.x(), ir.y(), ir.width(), ir.height(), Qt::AlignLeft | Qt::AlignVCenter | Qt::TextSingleLine, tb->text);
3529 }
3530
3531 ir = layout[SC_TitleBarSysMenu];
3532 if (ir.isValid()) {
3533 QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarSysMenu);
3534 subSubRule.drawRule(p, ir);
3535 ir = subSubRule.contentsRect(ir);
3536 if (!tb->icon.isNull()) {
3537 tb->icon.paint(p, ir);
3538 } else {
3539 int iconSize = pixelMetric(PM_SmallIconSize, tb, w);
3540 const QSize sz(iconSize, iconSize);
3541 const auto pm = standardIcon(SP_TitleBarMenuButton, nullptr, w)
3542 .pixmap(sz, paintDeviceDpr);
3543 drawItemPixmap(p, ir, Qt::AlignCenter, pm);
3544 }
3545 }
3546
3547 ir = layout[SC_TitleBarCloseButton];
3548 if (ir.isValid()) {
3549 QRenderRule subSubRule = renderRule(w, opt, PseudoElement_TitleBarCloseButton);
3550 subSubRule.drawRule(p, ir);
3551
3552 const QSize sz = subSubRule.contentsRect(ir).size();
3553 const auto type = ((tb->titleBarFlags & Qt::WindowType_Mask) == Qt::Tool)
3554 ? SP_DockWidgetCloseButton : SP_TitleBarCloseButton;
3555 const auto pm = standardIcon(type, nullptr, w).pixmap(sz, paintDeviceDpr);
3556 drawItemPixmap(p, ir, Qt::AlignCenter, pm);
3557 }
3558
3559 constexpr std::array<int, 6> pes = {
3560 PseudoElement_TitleBarMaxButton,
3561 PseudoElement_TitleBarMinButton,
3562 PseudoElement_TitleBarNormalButton,
3563 PseudoElement_TitleBarShadeButton,
3564 PseudoElement_TitleBarUnshadeButton,
3565 PseudoElement_TitleBarContextHelpButton
3566 };
3567
3568 for (int pe : pes) {
3569 QStyle::SubControl sc = knownPseudoElements[pe].subControl;
3570 ir = layout[sc];
3571 if (!ir.isValid())
3572 continue;
3573 QRenderRule subSubRule = renderRule(w, opt, pe);
3574 subSubRule.drawRule(p, ir);
3575 const QSize sz = subSubRule.contentsRect(ir).size();
3576 const auto pm = standardIcon(subControlIcon(pe), nullptr, w).pixmap(sz, paintDeviceDpr);
3577 drawItemPixmap(p, ir, Qt::AlignCenter, pm);
3578 }
3579
3580 return;
3581 }
3582 break;
3583
3584
3585 default:
3586 break;
3587 }
3588
3589 baseStyle()->drawComplexControl(cc, opt, p, w);
3590}
3591
3592void QStyleSheetStyle::renderMenuItemIcon(const QStyleOptionMenuItem *mi, QPainter *p, const QWidget *w,
3593 const QRect &rect, QRenderRule &subRule) const
3594{
3595 const QIcon::Mode mode = mi->state & QStyle::State_Enabled
3596 ? (mi->state & QStyle::State_Selected ? QIcon::Active : QIcon::Normal)
3597 : QIcon::Disabled;
3598 const bool checked = mi->checkType != QStyleOptionMenuItem::NotCheckable && mi->checked;
3599 const auto iconSize = pixelMetric(PM_SmallIconSize, mi, w);
3600 const QSize sz(iconSize, iconSize);
3601 const QPixmap pixmap(mi->icon.pixmap(sz, QStyleHelper::getDpr(p), mode,
3602 checked ? QIcon::On : QIcon::Off));
3603 const int pixw = pixmap.width() / pixmap.devicePixelRatio();
3604 const int pixh = pixmap.height() / pixmap.devicePixelRatio();
3605 QRenderRule iconRule = renderRule(w, mi, PseudoElement_MenuIcon);
3606 if (!iconRule.hasGeometry()) {
3607 iconRule.geo = new QStyleSheetGeometryData(pixw, pixh, pixw, pixh, -1, -1);
3608 } else {
3609 iconRule.geo->width = pixw;
3610 iconRule.geo->height = pixh;
3611 }
3612 QRect iconRect = positionRect(w, subRule, iconRule, PseudoElement_MenuIcon, rect, mi->direction);
3613 if (mi->direction == Qt::LeftToRight)
3614 iconRect.moveLeft(iconRect.left());
3615 else
3616 iconRect.moveRight(iconRect.right());
3617 iconRule.drawRule(p, iconRect);
3618 QRect pmr(0, 0, pixw, pixh);
3619 pmr.moveCenter(iconRect.center());
3620 p->drawPixmap(pmr.topLeft(), pixmap);
3621}
3622
3623void QStyleSheetStyle::drawControl(ControlElement ce, const QStyleOption *opt, QPainter *p,
3624 const QWidget *w) const
3625{
3626 RECURSION_GUARD(baseStyle()->drawControl(ce, opt, p, w); return)
3627
3628 QRenderRule rule = renderRule(w, opt);
3629 int pe1 = PseudoElement_None, pe2 = PseudoElement_None;
3630 bool fallback = false;
3631
3632 switch (ce) {
3633 case CE_ToolButtonLabel:
3634#if QT_CONFIG(toolbutton)
3635 if (const QStyleOptionToolButton *btn = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
3636 if (rule.hasBox() || btn->features & QStyleOptionToolButton::Arrow) {
3637 QWindowsStyle::drawControl(ce, opt, p, w);
3638 } else {
3639 QStyleOptionToolButton butOpt(*btn);
3640 rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
3641 baseStyle()->drawControl(ce, &butOpt, p, w);
3642 }
3643 return;
3644 }
3645#endif // QT_CONFIG(toolbutton)
3646 break;
3647
3648 case CE_FocusFrame:
3649 if (!rule.hasNativeBorder()) {
3650 rule.drawBorder(p, opt->rect);
3651 return;
3652 }
3653 break;
3654
3655 case CE_PushButton:
3656 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3657 if (rule.hasDrawable() || rule.hasBox() || rule.hasPosition() || rule.hasPalette() ||
3658 ((btn->features & QStyleOptionButton::HasMenu) && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator))) {
3659 ParentStyle::drawControl(ce, opt, p, w);
3660 return;
3661 }
3662 }
3663 break;
3664 case CE_PushButtonBevel:
3665 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3666 QStyleOptionButton btnOpt(*btn);
3667 btnOpt.rect = rule.borderRect(opt->rect);
3668 if (rule.hasNativeBorder()) {
3669 rule.drawBackgroundImage(p, btnOpt.rect);
3670 rule.configurePalette(&btnOpt.palette, QPalette::ButtonText, QPalette::Button);
3671 bool customMenu = (btn->features & QStyleOptionButton::HasMenu
3672 && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator));
3673 if (customMenu)
3674 btnOpt.features &= ~QStyleOptionButton::HasMenu;
3675 if (rule.baseStyleCanDraw()) {
3676 baseStyle()->drawControl(ce, &btnOpt, p, w);
3677 } else {
3678 QWindowsStyle::drawControl(ce, &btnOpt, p, w);
3679 }
3680 rule.drawImage(p, rule.contentsRect(opt->rect));
3681 if (!customMenu)
3682 return;
3683 } else {
3684 rule.drawRule(p, opt->rect);
3685 }
3686
3687 if (btn->features & QStyleOptionButton::HasMenu) {
3688 QRenderRule subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
3689 QRect ir = positionRect(w, rule, subRule, PseudoElement_PushButtonMenuIndicator,
3690 baseStyle()->subElementRect(SE_PushButtonBevel, btn, w), opt->direction);
3691
3692 // Move to the left to align with the other styles
3693 const int mbi = pixelMetric(PM_MenuButtonIndicator, &btnOpt, w);
3694 constexpr int horizontalExtraShift = -2;
3695
3696 ir = QRect(ir.right() - mbi + horizontalExtraShift, ir.y(), ir.width(), ir.height());
3697 if (subRule.hasDrawable()) {
3698 subRule.drawRule(p, ir);
3699 } else {
3700 btnOpt.rect = ir;
3701 baseStyle()->drawPrimitive(PE_IndicatorArrowDown, &btnOpt, p, w);
3702 }
3703 }
3704 }
3705 return;
3706
3707 case CE_PushButtonLabel:
3708 if (const QStyleOptionButton *button = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3709 QStyleOptionButton butOpt(*button);
3710 rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
3711
3712 const QFont oldFont = p->font();
3713 if (rule.hasFont)
3714 p->setFont(rule.font.resolve(p->font()));
3715
3716 if (rule.hasPosition() || rule.hasIcon()) {
3717 uint tf = Qt::TextShowMnemonic;
3718 QRect textRect = button->rect;
3719
3720 const uint horizontalAlignMask = Qt::AlignHCenter | Qt::AlignLeft | Qt::AlignRight;
3721 const uint verticalAlignMask = Qt::AlignVCenter | Qt::AlignTop | Qt::AlignBottom;
3722
3723 if (rule.hasPosition() && rule.position()->textAlignment != 0) {
3724 Qt::Alignment textAlignment = rule.position()->textAlignment;
3725 tf |= (textAlignment & verticalAlignMask) ? (textAlignment & verticalAlignMask) : Qt::AlignVCenter;
3726 tf |= (textAlignment & horizontalAlignMask) ? (textAlignment & horizontalAlignMask) : Qt::AlignHCenter;
3727 if (!styleHint(SH_UnderlineShortcut, button, w))
3728 tf |= Qt::TextHideMnemonic;
3729 } else {
3730 tf |= Qt::AlignVCenter | Qt::AlignHCenter;
3731 }
3732
3733 QIcon icon = rule.hasIcon() ? rule.icon()->icon : button->icon;
3734 if (!icon.isNull()) {
3735 //Group both icon and text
3736 QRect iconRect;
3737 QIcon::Mode mode = button->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
3738 if (mode == QIcon::Normal && button->state & State_HasFocus)
3739 mode = QIcon::Active;
3740 QIcon::State state = QIcon::Off;
3741 if (button->state & State_On)
3742 state = QIcon::On;
3743
3744 const auto paintDeviceDpr = QStyleHelper::getDpr(p);
3745 QPixmap pixmap = icon.pixmap(button->iconSize, paintDeviceDpr, mode, state);
3746 int pixmapWidth = pixmap.width() / pixmap.devicePixelRatio();
3747 int pixmapHeight = pixmap.height() / pixmap.devicePixelRatio();
3748 int labelWidth = pixmapWidth;
3749 int labelHeight = pixmapHeight;
3750 int iconSpacing = 4;//### 4 is currently hardcoded in QPushButton::sizeHint()
3751 int textWidth = button->fontMetrics.boundingRect(opt->rect, tf, button->text).width();
3752 if (!button->text.isEmpty())
3753 labelWidth += (textWidth + iconSpacing);
3754
3755 //Determine label alignment:
3756 if (tf & Qt::AlignLeft) { /*left*/
3757 iconRect = QRect(textRect.x(), textRect.y() + (textRect.height() - labelHeight) / 2,
3758 pixmapWidth, pixmapHeight);
3759 } else if (tf & Qt::AlignHCenter) { /* center */
3760 iconRect = QRect(textRect.x() + (textRect.width() - labelWidth) / 2,
3761 textRect.y() + (textRect.height() - labelHeight) / 2,
3762 pixmapWidth, pixmapHeight);
3763 } else { /*right*/
3764 iconRect = QRect(textRect.x() + textRect.width() - labelWidth,
3765 textRect.y() + (textRect.height() - labelHeight) / 2,
3766 pixmapWidth, pixmapHeight);
3767 }
3768
3769 iconRect = visualRect(button->direction, textRect, iconRect);
3770
3771 // Left align, adjust the text-rect according to the icon instead
3772 tf &= ~horizontalAlignMask;
3773 tf |= Qt::AlignLeft;
3774
3775 if (button->direction == Qt::RightToLeft)
3776 textRect.setRight(iconRect.left() - iconSpacing);
3777 else
3778 textRect.setLeft(iconRect.left() + iconRect.width() + iconSpacing);
3779
3780 if (button->state & (State_On | State_Sunken))
3781 iconRect.translate(pixelMetric(PM_ButtonShiftHorizontal, opt, w),
3782 pixelMetric(PM_ButtonShiftVertical, opt, w));
3783 p->drawPixmap(iconRect, pixmap);
3784 }
3785
3786 if (button->state & (State_On | State_Sunken))
3787 textRect.translate(pixelMetric(PM_ButtonShiftHorizontal, opt, w),
3788 pixelMetric(PM_ButtonShiftVertical, opt, w));
3789
3790 if (button->features & QStyleOptionButton::HasMenu) {
3791 int indicatorSize = pixelMetric(PM_MenuButtonIndicator, button, w);
3792 if (button->direction == Qt::LeftToRight)
3793 textRect = textRect.adjusted(0, 0, -indicatorSize, 0);
3794 else
3795 textRect = textRect.adjusted(indicatorSize, 0, 0, 0);
3796 }
3797 drawItemText(p, textRect, tf, butOpt.palette, (button->state & State_Enabled),
3798 button->text, QPalette::ButtonText);
3799 } else {
3800 ParentStyle::drawControl(ce, &butOpt, p, w);
3801 }
3802
3803 if (rule.hasFont)
3804 p->setFont(oldFont);
3805 }
3806 return;
3807
3808 case CE_RadioButton:
3809 case CE_CheckBox:
3810 if (rule.hasBox() || !rule.hasNativeBorder() || rule.hasDrawable() || hasStyleRule(w, PseudoElement_Indicator)) {
3811 rule.drawRule(p, opt->rect);
3812 ParentStyle::drawControl(ce, opt, p, w);
3813 return;
3814 } else if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3815 QStyleOptionButton butOpt(*btn);
3816 rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
3817 baseStyle()->drawControl(ce, &butOpt, p, w);
3818 return;
3819 }
3820 break;
3821 case CE_RadioButtonLabel:
3822 case CE_CheckBoxLabel:
3823 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
3824 QStyleOptionButton butOpt(*btn);
3825 rule.configurePalette(&butOpt.palette, QPalette::ButtonText, QPalette::Button);
3826 ParentStyle::drawControl(ce, &butOpt, p, w);
3827 }
3828 return;
3829
3830 case CE_Splitter:
3831 pe1 = PseudoElement_SplitterHandle;
3832 break;
3833
3834 case CE_ToolBar:
3835 if (rule.hasBackground()) {
3836 rule.drawBackground(p, opt->rect);
3837 }
3838 if (rule.hasBorder()) {
3839 rule.drawBorder(p, rule.borderRect(opt->rect));
3840 } else {
3841#if QT_CONFIG(toolbar)
3842 if (const QStyleOptionToolBar *tb = qstyleoption_cast<const QStyleOptionToolBar *>(opt)) {
3843 QStyleOptionToolBar newTb(*tb);
3844 newTb.rect = rule.borderRect(opt->rect);
3845 baseStyle()->drawControl(ce, &newTb, p, w);
3846 }
3847#endif // QT_CONFIG(toolbar)
3848 }
3849 return;
3850
3851 case CE_MenuEmptyArea:
3852 case CE_MenuBarEmptyArea:
3853 if (rule.hasDrawable()) {
3854 // Drawn by PE_Widget
3855 return;
3856 }
3857 break;
3858
3859 case CE_MenuTearoff:
3860 case CE_MenuScroller:
3861 if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
3862 QStyleOptionMenuItem mi(*m);
3863 int pe = ce == CE_MenuTearoff ? PseudoElement_MenuTearoff : PseudoElement_MenuScroller;
3864 QRenderRule subRule = renderRule(w, opt, pe);
3865 mi.rect = subRule.contentsRect(opt->rect);
3866 rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
3867 subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
3868
3869 if (subRule.hasDrawable()) {
3870 subRule.drawRule(p, opt->rect);
3871 } else {
3872 baseStyle()->drawControl(ce, &mi, p, w);
3873 }
3874 }
3875 return;
3876
3877 case CE_MenuItem:
3878 if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
3879 QStyleOptionMenuItem mi(*m);
3880
3881 int pseudo = (mi.menuItemType == QStyleOptionMenuItem::Separator) ? PseudoElement_MenuSeparator : PseudoElement_Item;
3882 QRenderRule subRule = renderRule(w, opt, pseudo);
3883 mi.rect = subRule.contentsRect(opt->rect);
3884 rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
3885 rule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
3886 subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
3887 subRule.configurePalette(&mi.palette, QPalette::HighlightedText, QPalette::Highlight);
3888 QFont oldFont = p->font();
3889 if (subRule.hasFont)
3890 p->setFont(subRule.font.resolve(mi.font));
3891 else
3892 p->setFont(mi.font);
3893
3894 // We fall back to drawing with the style sheet code whenever at least one of the
3895 // items are styled in an incompatible way, such as having a background image.
3896 QRenderRule allRules = renderRule(w, PseudoElement_Item, PseudoClass_Any);
3897
3898 if ((pseudo == PseudoElement_MenuSeparator) && subRule.hasDrawable()) {
3899 subRule.drawRule(p, opt->rect);
3900 } else if ((pseudo == PseudoElement_Item)
3901 && (allRules.hasBox() || allRules.hasBorder() || subRule.hasFont
3902 || (allRules.background() && !allRules.background()->pixmap.isNull()))) {
3903 subRule.drawRule(p, opt->rect);
3904 if (subRule.hasBackground()) {
3905 mi.palette.setBrush(QPalette::Highlight, Qt::NoBrush);
3906 mi.palette.setBrush(QPalette::Button, Qt::NoBrush);
3907 } else {
3908 mi.palette.setBrush(QPalette::Highlight, mi.palette.brush(QPalette::Button));
3909 }
3910 mi.palette.setBrush(QPalette::HighlightedText, mi.palette.brush(QPalette::ButtonText));
3911
3912 bool drawCheckMark = mi.menuHasCheckableItems;
3913#if QT_CONFIG(combobox)
3914 if (qobject_cast<const QComboBox *>(w))
3915 drawCheckMark = false; // ignore the checkmarks provided by the QComboMenuDelegate
3916#endif
3917 int textRectOffset = m->maxIconWidth;
3918 if (!mi.icon.isNull()) {
3919 renderMenuItemIcon(&mi, p, w, opt->rect, subRule);
3920 } else if (drawCheckMark) {
3921 const bool checkable = mi.checkType != QStyleOptionMenuItem::NotCheckable;
3922 const bool checked = checkable ? mi.checked : false;
3923
3924 const QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
3925 const QRect cmRect = positionRect(w, subRule, subSubRule, PseudoElement_MenuCheckMark, opt->rect, opt->direction);
3926 if (checkable && (subSubRule.hasDrawable() || checked)) {
3927 QStyleOptionMenuItem newMi = mi;
3928 if (opt->state & QStyle::State_Enabled)
3929 newMi.state |= State_Enabled;
3930 if (mi.checked)
3931 newMi.state |= State_On;
3932 newMi.rect = cmRect;
3933 drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, w);
3934 }
3935 textRectOffset = std::max(m->maxIconWidth, cmRect.width());
3936 }
3937
3938 QRect textRect = subRule.contentsRect(opt->rect);
3939 textRect.setLeft(textRect.left() + textRectOffset);
3940 textRect.setWidth(textRect.width() - mi.reservedShortcutWidth);
3941 const QRect vTextRect = visualRect(opt->direction, m->rect, textRect);
3942
3943 QStringView s(mi.text);
3944 p->setPen(mi.palette.buttonText().color());
3945 if (!s.isEmpty()) {
3946 int text_flags = Qt::AlignLeft | Qt::AlignVCenter | Qt::TextShowMnemonic | Qt::TextDontClip | Qt::TextSingleLine;
3947 if (!styleHint(SH_UnderlineShortcut, &mi, w))
3948 text_flags |= Qt::TextHideMnemonic;
3949 qsizetype t = s.indexOf(u'\t');
3950 if (t >= 0) {
3951 QRect vShortcutRect = visualRect(opt->direction, mi.rect,
3952 QRect(textRect.topRight(), QPoint(mi.rect.right(), textRect.bottom())));
3953 p->drawText(vShortcutRect, text_flags, s.mid(t + 1).toString());
3954 s = s.left(t);
3955 }
3956 p->drawText(vTextRect, text_flags, s.left(t).toString());
3957 }
3958
3959 if (mi.menuItemType == QStyleOptionMenuItem::SubMenu) {// draw sub menu arrow
3960 PrimitiveElement arrow = (opt->direction == Qt::RightToLeft) ? PE_IndicatorArrowLeft : PE_IndicatorArrowRight;
3961 QRenderRule subRule2 = renderRule(w, opt, PseudoElement_MenuRightArrow);
3962 if (subRule2.hasContentsSize()) {
3963 mi.rect = positionRect(w, subRule, subRule2, PseudoElement_MenuRightArrow, opt->rect, mi.direction);
3964 } else {
3965 // Derive arrow size from the item height
3966 int dim = opt->rect.height() / 2;
3967 QRect arrowRect(0, 0, dim, dim);
3968 // Right-align arrow
3969 arrowRect.moveCenter(QPoint(opt->rect.right() - dim, opt->rect.center().y()));
3970 mi.rect = visualRect(opt->direction, opt->rect, arrowRect);
3971 }
3972
3973 drawPrimitive(arrow, &mi, p, w);
3974 }
3975 } else if (!mi.icon.isNull() && hasStyleRule(w, PseudoElement_MenuIcon)) {
3976 // we wouldn't be here if the item itself would be styled, so now we only want
3977 // the text from the default style, and then draw the icon ourselves.
3978 QStyleOptionMenuItem newMi = mi;
3979 newMi.icon = {};
3980 newMi.checkType = QStyleOptionMenuItem::NotCheckable;
3981 if (rule.baseStyleCanDraw() && subRule.baseStyleCanDraw())
3982 baseStyle()->drawControl(ce, &newMi, p, w);
3983 else
3984 ParentStyle::drawControl(ce, &newMi, p, w);
3985 renderMenuItemIcon(&mi, p, w, opt->rect, subRule);
3986 } else if (hasStyleRule(w, PseudoElement_MenuCheckMark) || hasStyleRule(w, PseudoElement_MenuRightArrow)) {
3987 QWindowsStyle::drawControl(ce, &mi, p, w);
3988 if (mi.checkType != QStyleOptionMenuItem::NotCheckable && !mi.checked) {
3989 // We have a style defined, but QWindowsStyle won't draw anything if not checked.
3990 // So we mimic what QWindowsStyle would do.
3991 int checkcol = qMax<int>(mi.maxIconWidth, QWindowsStylePrivate::windowsCheckMarkWidth);
3992 QRect vCheckRect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x(), mi.rect.y(), checkcol, mi.rect.height()));
3993 if (mi.state.testFlag(State_Enabled) && mi.state.testFlag(State_Selected)) {
3994 qDrawShadePanel(p, vCheckRect, mi.palette, true, 1, &mi.palette.brush(QPalette::Button));
3995 } else {
3996 QBrush fill(mi.palette.light().color(), Qt::Dense4Pattern);
3997 qDrawShadePanel(p, vCheckRect, mi.palette, true, 1, &fill);
3998 }
3999 QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
4000 if (subSubRule.hasDrawable()) {
4001 QStyleOptionMenuItem newMi(mi);
4002 newMi.rect = visualRect(opt->direction, mi.rect, QRect(mi.rect.x() + QWindowsStylePrivate::windowsItemFrame,
4003 mi.rect.y() + QWindowsStylePrivate::windowsItemFrame,
4004 checkcol - 2 * QWindowsStylePrivate::windowsItemFrame,
4005 mi.rect.height() - 2 * QWindowsStylePrivate::windowsItemFrame));
4006 drawPrimitive(PE_IndicatorMenuCheckMark, &newMi, p, w);
4007 }
4008 }
4009 } else {
4010 if (rule.hasDrawable() && !subRule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
4011 mi.palette.setColor(QPalette::Window, Qt::transparent);
4012 mi.palette.setColor(QPalette::Button, Qt::transparent);
4013 }
4014 if (rule.baseStyleCanDraw() && subRule.baseStyleCanDraw()) {
4015 baseStyle()->drawControl(ce, &mi, p, w);
4016 } else {
4017 ParentStyle::drawControl(ce, &mi, p, w);
4018 }
4019 }
4020
4021 p->setFont(oldFont);
4022
4023 return;
4024 }
4025 return;
4026
4027 case CE_MenuBarItem:
4028 if (const QStyleOptionMenuItem *m = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
4029 QStyleOptionMenuItem mi(*m);
4030 QRenderRule subRule = renderRule(w, opt, PseudoElement_Item);
4031 mi.rect = subRule.contentsRect(opt->rect);
4032 rule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
4033 subRule.configurePalette(&mi.palette, QPalette::ButtonText, QPalette::Button);
4034
4035 if (subRule.hasDrawable()) {
4036 subRule.drawRule(p, opt->rect);
4037 // AXIVION Next Line Qt-SkippedBaseMethod: deliberate bypass of the base
4038 QCommonStyle::drawControl(ce, &mi, p, w);
4039 } else {
4040 if (rule.hasDrawable() && !(opt->state & QStyle::State_Selected)) {
4041 // So that the menu bar background is not hidden by the items
4042 mi.palette.setColor(QPalette::Window, Qt::transparent);
4043 mi.palette.setColor(QPalette::Button, Qt::transparent);
4044 }
4045 baseStyle()->drawControl(ce, &mi, p, w);
4046 }
4047 }
4048 return;
4049
4050#if QT_CONFIG(combobox)
4051 case CE_ComboBoxLabel:
4052 if (!rule.hasDrawable())
4053 break;
4054 if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
4055 QRect editRect = subControlRect(CC_ComboBox, cb, SC_ComboBoxEditField, w);
4056 p->save();
4057 p->setClipRect(editRect);
4058 if (!cb->currentIcon.isNull()) {
4059 int spacing = rule.hasBox() ? rule.box()->spacing : -1;
4060 if (spacing == -1)
4061 spacing = 6;
4062 QIcon::Mode mode = cb->state & State_Enabled ? QIcon::Normal : QIcon::Disabled;
4063 const auto paintDeviceDpr = QStyleHelper::getDpr(p);
4064 QPixmap pixmap = cb->currentIcon.pixmap(cb->iconSize, paintDeviceDpr, mode);
4065 QRect iconRect(editRect);
4066 iconRect.setWidth(cb->iconSize.width());
4067 iconRect = alignedRect(cb->direction,
4068 Qt::AlignLeft | Qt::AlignVCenter,
4069 iconRect.size(), editRect);
4070 drawItemPixmap(p, iconRect, Qt::AlignCenter, pixmap);
4071
4072 if (cb->direction == Qt::RightToLeft)
4073 editRect.translate(-spacing - cb->iconSize.width(), 0);
4074 else
4075 editRect.translate(cb->iconSize.width() + spacing, 0);
4076 }
4077 if (!cb->currentText.isEmpty() && !cb->editable) {
4078 QPalette styledPalette(cb->palette);
4079 rule.configurePalette(&styledPalette, QPalette::Text, QPalette::Base);
4080 drawItemText(p, editRect.adjusted(0, 0, 0, 0), cb->textAlignment, styledPalette,
4081 cb->state & State_Enabled, cb->currentText, QPalette::Text);
4082 }
4083 p->restore();
4084 return;
4085 }
4086 break;
4087#endif // QT_CONFIG(combobox)
4088
4089 case CE_Header:
4090 if (hasStyleRule(w, PseudoElement_HeaderViewUpArrow)
4091 || hasStyleRule(w, PseudoElement_HeaderViewDownArrow)) {
4092 ParentStyle::drawControl(ce, opt, p, w);
4093 return;
4094 }
4095 if (hasStyleRule(w, PseudoElement_HeaderViewSection)) {
4096 QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
4097 if (!subRule.hasNativeBorder() || !subRule.baseStyleCanDraw()
4098 || subRule.hasBackground() || subRule.hasPalette() || subRule.hasFont || subRule.hasBorder()) {
4099 ParentStyle::drawControl(ce, opt, p, w);
4100 return;
4101 }
4102 }
4103 break;
4104 case CE_HeaderSection:
4105 if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
4106 QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
4107 if (subRule.hasNativeBorder()) {
4108 QStyleOptionHeader hdr(*header);
4109 subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
4110
4111 if (subRule.baseStyleCanDraw()) {
4112 baseStyle()->drawControl(CE_HeaderSection, &hdr, p, w);
4113 } else {
4114 QWindowsStyle::drawControl(CE_HeaderSection, &hdr, p, w);
4115 }
4116 } else {
4117 subRule.drawRule(p, opt->rect);
4118 }
4119 return;
4120 }
4121 break;
4122
4123 case CE_HeaderLabel:
4124 if (const QStyleOptionHeader *header = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
4125 // Save painter state
4126 QPainterStateGuard psGuard(p);
4127
4128 QStyleOptionHeaderV2 hdr;
4129 QStyleOptionHeader &v1Copy = hdr;
4130 if (auto v2 = qstyleoption_cast<const QStyleOptionHeaderV2 *>(header))
4131 hdr = *v2;
4132 else
4133 v1Copy = *header;
4134
4135 QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
4136 if (hasStyleRule(w, PseudoElement_HeaderViewUpArrow)
4137 || hasStyleRule(w, PseudoElement_HeaderViewDownArrow)) {
4138 if (hdr.sortIndicator != QStyleOptionHeader::None) {
4139 QRegion newClipRegion = QRegion(hdr.rect);
4140 const QRect arrowRect = subElementRect(SE_HeaderArrow, opt, w);
4141 const QRenderRule hrRule = renderRule(w, opt, PseudoElement_HeaderViewUpArrow);
4142 // Clip the text to avoid overlapping with the sort arrow if
4143 // the sort arrow is aligned to the right or left if horizontal
4144 // or top or bottom if vertical.
4145 if (hrRule.hasPosition()) {
4146 const auto position = hrRule.position()->position;
4147 if (hdr.orientation == Qt::Horizontal) {
4148 if (position & Qt::AlignLeft) {
4149 newClipRegion -= QRegion(arrowRect.x(), hdr.rect.y(),
4150 arrowRect.width(), hdr.rect.height());
4151 } else if (position & Qt::AlignRight) {
4152 newClipRegion -= QRegion(arrowRect.x(), hdr.rect.y(),
4153 arrowRect.width(), hdr.rect.height());
4154 }
4155 } else if (hdr.orientation == Qt::Vertical) {
4156 if (position & Qt::AlignTop) {
4157 newClipRegion -= QRegion(arrowRect.x(), hdr.rect.y(),
4158 hdr.rect.width(), arrowRect.height());
4159 } else if (position & Qt::AlignBottom) {
4160 newClipRegion -= QRegion(arrowRect.x(), arrowRect.y(),
4161 hdr.rect.width(), arrowRect.height());
4162 }
4163 }
4164 }
4165 p->setClipping(true);
4166 p->setClipRegion(newClipRegion);
4167 }
4168 }
4169
4170 subRule.configurePalette(&hdr.palette, QPalette::ButtonText, QPalette::Button);
4171
4172 if (subRule.hasFont) {
4173 p->setFont(subRule.font.resolve(p->font()));
4174 ParentStyle::drawControl(ce, &hdr, p, w);
4175 } else {
4176 baseStyle()->drawControl(ce, &hdr, p, w);
4177 }
4178 return;
4179 }
4180 break;
4181
4182 case CE_HeaderEmptyArea:
4183 if (rule.hasDrawable()) {
4184 return;
4185 }
4186 break;
4187
4188 case CE_ProgressBar:
4189 QWindowsStyle::drawControl(ce, opt, p, w);
4190 return;
4191
4192 case CE_ProgressBarGroove:
4193 if (!rule.hasNativeBorder()) {
4194 rule.drawRule(p, rule.boxRect(opt->rect, Margin));
4195 return;
4196 }
4197 break;
4198
4199 case CE_ProgressBarContents: {
4200 QRenderRule subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
4201 if (subRule.hasDrawable()) {
4202 if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
4203 p->save();
4204 p->setClipRect(pb->rect);
4205
4206 qint64 minimum = qint64(pb->minimum);
4207 qint64 maximum = qint64(pb->maximum);
4208 qint64 progress = qint64(pb->progress);
4209 bool vertical = !(pb->state & QStyle::State_Horizontal);
4210 bool inverted = pb->invertedAppearance;
4211
4212 QTransform m;
4213 QRect rect = pb->rect;
4214 if (vertical) {
4215 rect = QRect(rect.y(), rect.x(), rect.height(), rect.width());
4216 m.rotate(90);
4217 m.translate(0, -(rect.height() + rect.y()*2));
4218 }
4219
4220 bool reverse = ((!vertical && (pb->direction == Qt::RightToLeft)) || vertical);
4221 if (inverted)
4222 reverse = !reverse;
4223 const bool indeterminate = pb->minimum == pb->maximum;
4224 const auto fillRatio = indeterminate ? 0.50 : double(progress - minimum) / (maximum - minimum);
4225 const auto fillWidth = static_cast<int>(rect.width() * fillRatio);
4226 int chunkWidth = fillWidth;
4227 if (subRule.hasContentsSize()) {
4228 QSize sz = subRule.size();
4229 chunkWidth = (opt->state & QStyle::State_Horizontal) ? sz.width() : sz.height();
4230 }
4231
4232 QRect r = rect;
4233#if QT_CONFIG(animation)
4234 Q_D(const QWindowsStyle);
4235#endif
4236 if (pb->minimum == 0 && pb->maximum == 0) {
4237 int chunkCount = fillWidth/chunkWidth;
4238 int offset = 0;
4239#if QT_CONFIG(animation)
4240 if (QProgressStyleAnimation *animation = qobject_cast<QProgressStyleAnimation*>(d->animation(opt->styleObject)))
4241 offset = animation->animationStep() * 8 % rect.width();
4242 else
4243 d->startAnimation(new QProgressStyleAnimation(d->animationFps, opt->styleObject));
4244#endif
4245 int x = reverse ? r.left() + r.width() - offset - chunkWidth : r.x() + offset;
4246 while (chunkCount > 0) {
4247 r.setRect(x, rect.y(), chunkWidth, rect.height());
4248 r = m.mapRect(QRectF(r)).toRect();
4249 subRule.drawRule(p, r);
4250 x += reverse ? -chunkWidth : chunkWidth;
4251 if (reverse ? x < rect.left() : x > rect.right())
4252 break;
4253 --chunkCount;
4254 }
4255
4256 r = rect;
4257 x = reverse ? r.right() - (r.left() - x - chunkWidth)
4258 : r.left() + (x - r.right() - chunkWidth);
4259 while (chunkCount > 0) {
4260 r.setRect(x, rect.y(), chunkWidth, rect.height());
4261 r = m.mapRect(QRectF(r)).toRect();
4262 subRule.drawRule(p, r);
4263 x += reverse ? -chunkWidth : chunkWidth;
4264 --chunkCount;
4265 };
4266 } else if (chunkWidth > 0) {
4267 const auto ceil = [](qreal x) { return int(x) + (x > 0 && x != int(x)); };
4268 const int chunkCount = ceil(qreal(fillWidth)/chunkWidth);
4269 int x = reverse ? r.left() + r.width() - chunkWidth : r.x();
4270
4271 for (int i = 0; i < chunkCount; ++i) {
4272 r.setRect(x, rect.y(), chunkWidth, rect.height());
4273 r = m.mapRect(QRectF(r)).toRect();
4274 subRule.drawRule(p, r);
4275 x += reverse ? -chunkWidth : chunkWidth;
4276 }
4277#if QT_CONFIG(animation)
4278 d->stopAnimation(opt->styleObject);
4279#endif
4280 }
4281
4282 p->restore();
4283 return;
4284 }
4285 }
4286 }
4287 break;
4288
4289 case CE_ProgressBarLabel:
4290 if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
4291 if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_ProgressBarChunk)) {
4292 drawItemText(p, pb->rect, pb->textAlignment | Qt::TextSingleLine, pb->palette,
4293 pb->state & State_Enabled, pb->text, QPalette::Text);
4294 } else {
4295 QStyleOptionProgressBar pbCopy(*pb);
4296 rule.configurePalette(&pbCopy.palette, QPalette::HighlightedText, QPalette::Highlight);
4297 baseStyle()->drawControl(ce, &pbCopy, p, w);
4298 }
4299 return;
4300 }
4301 break;
4302
4303 case CE_SizeGrip:
4304 if (const QStyleOptionSizeGrip *sgOpt = qstyleoption_cast<const QStyleOptionSizeGrip *>(opt)) {
4305 if (rule.hasDrawable()) {
4306 rule.drawFrame(p, opt->rect);
4307 p->save();
4308 static constexpr int rotation[] = { 180, 270, 90, 0 };
4309 if (rotation[sgOpt->corner]) {
4310 p->translate(opt->rect.center());
4311 p->rotate(rotation[sgOpt->corner]);
4312 p->translate(-opt->rect.center());
4313 }
4314 rule.drawImage(p, opt->rect);
4315 p->restore();
4316 } else {
4317 QStyleOptionSizeGrip sg(*sgOpt);
4318 sg.rect = rule.contentsRect(opt->rect);
4319 baseStyle()->drawControl(CE_SizeGrip, &sg, p, w);
4320 }
4321 return;
4322 }
4323 break;
4324
4325 case CE_ToolBoxTab:
4326 QWindowsStyle::drawControl(ce, opt, p, w);
4327 return;
4328
4329 case CE_ToolBoxTabShape: {
4330 QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolBoxTab);
4331 if (subRule.hasDrawable()) {
4332 subRule.drawRule(p, opt->rect);
4333 return;
4334 }
4335 }
4336 break;
4337
4338 case CE_ToolBoxTabLabel:
4339 if (const QStyleOptionToolBox *box = qstyleoption_cast<const QStyleOptionToolBox *>(opt)) {
4340 QStyleOptionToolBox boxCopy(*box);
4341 QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolBoxTab);
4342 subRule.configurePalette(&boxCopy.palette, QPalette::ButtonText, QPalette::Button);
4343 QFont oldFont = p->font();
4344 if (subRule.hasFont)
4345 p->setFont(subRule.font.resolve(p->font()));
4346 boxCopy.rect = subRule.contentsRect(opt->rect);
4347 if (subRule.hasImage()) {
4348 // the image is already drawn with CE_ToolBoxTabShape, adjust rect here
4349 const int iconExtent = proxy()->pixelMetric(QStyle::PM_SmallIconSize, box, w);
4350 boxCopy.rect.setLeft(boxCopy.rect.left() + iconExtent);
4351 }
4352 QWindowsStyle::drawControl(ce, &boxCopy, p , w);
4353 if (subRule.hasFont)
4354 p->setFont(oldFont);
4355 return;
4356 }
4357 break;
4358
4359 case CE_ScrollBarAddPage:
4360 pe1 = PseudoElement_ScrollBarAddPage;
4361 break;
4362
4363 case CE_ScrollBarSubPage:
4364 pe1 = PseudoElement_ScrollBarSubPage;
4365 break;
4366
4367 case CE_ScrollBarAddLine:
4368 pe1 = PseudoElement_ScrollBarAddLine;
4369 pe2 = (opt->state & QStyle::State_Horizontal) ? PseudoElement_ScrollBarRightArrow : PseudoElement_ScrollBarDownArrow;
4370 fallback = true;
4371 break;
4372
4373 case CE_ScrollBarSubLine:
4374 pe1 = PseudoElement_ScrollBarSubLine;
4375 pe2 = (opt->state & QStyle::State_Horizontal) ? PseudoElement_ScrollBarLeftArrow : PseudoElement_ScrollBarUpArrow;
4376 fallback = true;
4377 break;
4378
4379 case CE_ScrollBarFirst:
4380 pe1 = PseudoElement_ScrollBarFirst;
4381 break;
4382
4383 case CE_ScrollBarLast:
4384 pe1 = PseudoElement_ScrollBarLast;
4385 break;
4386
4387 case CE_ScrollBarSlider:
4388 pe1 = PseudoElement_ScrollBarSlider;
4389 fallback = true;
4390 break;
4391
4392#if QT_CONFIG(itemviews)
4393 case CE_ItemViewItem:
4394 if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
4395 QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
4396 QStyleOptionViewItem optCopy(*vopt);
4397 if (subRule.hasDrawable()) {
4398 subRule.configurePalette(&optCopy.palette, vopt->state & QStyle::State_Selected ? QPalette::HighlightedText : QPalette::Text,
4399 vopt->state & QStyle::State_Selected ? QPalette::Highlight : QPalette::Base);
4400 QWindowsStyle::drawControl(ce, &optCopy, p, w);
4401 } else {
4402 p->save();
4403 if (hasStyleRule(w, PseudoElement_Indicator)) {
4404 // there is a rule for the indicator, but no rule for the item itself (otherwise
4405 // the previous path would have been taken); only draw the indicator using the
4406 // rule (via QWindows/QCommonStyle), then let the base style handle the rest.
4407 QStyleOptionViewItem optIndicator(*vopt);
4408 subRule.configurePalette(&optIndicator.palette,
4409 vopt->state & QStyle::State_Selected
4410 ? QPalette::HighlightedText
4411 : QPalette::Text,
4412 vopt->state & QStyle::State_Selected
4413 ? QPalette::Highlight
4414 : QPalette::Base);
4415 // only draw the indicator; no text, icon or background
4416 optIndicator.backgroundBrush = Qt::NoBrush; // no background
4417 optIndicator.text.clear();
4418 optIndicator.icon = QIcon();
4419 QWindowsStyle::drawControl(ce, &optIndicator, p, w);
4420
4421 // Now draw text, background,icon, and highlight, but not the indicator with
4422 // the base style. Since we can't turn off HasCheckIndicator to prevent the base
4423 // style from drawing the check indicator again (it would change how the item
4424 // gets laid out) we have to clip the indicator that's already been painted.
4425 const QRect crStyle = subElementRect(QStyle::SE_ItemViewItemCheckIndicator,
4426 &optIndicator, w);
4427 const QRect crBase = baseStyle()->subElementRect(QStyle::SE_ItemViewItemCheckIndicator,
4428 &optIndicator, w);
4429 const QRegion clipRegion = QRegion(p->hasClipping() ? p->clipRegion()
4430 : QRegion(optIndicator.rect))
4431 - crStyle.united(crBase);
4432 p->setClipRegion(clipRegion);
4433 }
4434 subRule.configurePalette(&optCopy.palette, QPalette::Text, QPalette::NoRole);
4435 QStyleSheetProxySaver proxySaver(this);
4436 baseStyle()->drawControl(ce, &optCopy, p, w);
4437 p->restore();
4438 }
4439 return;
4440 }
4441 break;
4442#endif // QT_CONFIG(itemviews)
4443
4444#if QT_CONFIG(tabbar)
4445 case CE_TabBarTab:
4446 if (hasStyleRule(w, PseudoElement_TabBarTab)) {
4447 QWindowsStyle::drawControl(ce, opt, p, w);
4448 return;
4449 }
4450 break;
4451
4452 case CE_TabBarTabLabel:
4453 case CE_TabBarTabShape:
4454 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
4455 const auto foregroundRole = w ? w->foregroundRole() : QPalette::WindowText;
4456 QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
4457 QRect r = positionRect(w, subRule, PseudoElement_TabBarTab, opt->rect, opt->direction);
4458 if (ce == CE_TabBarTabShape && subRule.hasDrawable() && tab->shape < QTabBar::TriangularNorth) {
4459 subRule.drawRule(p, r);
4460 return;
4461 }
4462 QStyleOptionTab tabCopy(*tab);
4463 subRule.configurePalette(&tabCopy.palette, foregroundRole, QPalette::Base);
4464 QFont oldFont = p->font();
4465 if (subRule.hasFont)
4466 p->setFont(subRule.font.resolve(p->font()));
4467 if (subRule.hasBox() || !subRule.hasNativeBorder()) {
4468 tabCopy.rect = ce == CE_TabBarTabShape ? subRule.borderRect(r)
4469 : subRule.contentsRect(r);
4470 QWindowsStyle::drawControl(ce, &tabCopy, p, w);
4471 } else {
4472 baseStyle()->drawControl(ce, &tabCopy, p, w);
4473 }
4474 if (subRule.hasFont)
4475 p->setFont(oldFont);
4476
4477 return;
4478 }
4479 break;
4480#endif // QT_CONFIG(tabbar)
4481
4482 case CE_ColumnViewGrip:
4483 if (rule.hasDrawable()) {
4484 rule.drawRule(p, opt->rect);
4485 return;
4486 }
4487 break;
4488
4489 case CE_DockWidgetTitle:
4490 if (const QStyleOptionDockWidget *dwOpt = qstyleoption_cast<const QStyleOptionDockWidget *>(opt)) {
4491 QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
4492 if (!subRule.hasDrawable() && !subRule.hasPosition())
4493 break;
4494 if (subRule.hasDrawable()) {
4495 subRule.drawRule(p, opt->rect);
4496 } else {
4497 QStyleOptionDockWidget dwCopy(*dwOpt);
4498 dwCopy.title = QString();
4499 baseStyle()->drawControl(ce, &dwCopy, p, w);
4500 }
4501
4502 if (!dwOpt->title.isEmpty()) {
4503 QRect r = subElementRect(SE_DockWidgetTitleBarText, opt, w);
4504 if (dwOpt->verticalTitleBar) {
4505 r = r.transposed();
4506 p->save();
4507 p->translate(r.left(), r.top() + r.width());
4508 p->rotate(-90);
4509 p->translate(-r.left(), -r.top());
4510 }
4511 r = subRule.contentsRect(r);
4512
4513 Qt::Alignment alignment;
4514 if (subRule.hasPosition())
4515 alignment = subRule.position()->textAlignment;
4516 if (alignment == 0)
4517 alignment = Qt::AlignLeft;
4518
4519 QString titleText = p->fontMetrics().elidedText(dwOpt->title, Qt::ElideRight, r.width());
4520 drawItemText(p, r,
4521 alignment | Qt::TextHideMnemonic, dwOpt->palette,
4522 dwOpt->state & State_Enabled, titleText,
4523 QPalette::WindowText);
4524
4525 if (dwOpt->verticalTitleBar)
4526 p->restore();
4527 }
4528
4529 return;
4530 }
4531 break;
4532 case CE_ShapedFrame:
4533 if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
4534 if (rule.hasNativeBorder()) {
4535 QStyleOptionFrame frmOpt(*frm);
4536 rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
4537 frmOpt.rect = rule.borderRect(frmOpt.rect);
4538 baseStyle()->drawControl(ce, &frmOpt, p, w);
4539 }
4540 // else, borders are already drawn in PE_Widget
4541 }
4542 return;
4543
4544
4545 default:
4546 break;
4547 }
4548
4549 if (pe1 != PseudoElement_None) {
4550 QRenderRule subRule = renderRule(w, opt, pe1);
4551 if (subRule.bg != nullptr || subRule.hasDrawable()) {
4552 //We test subRule.bg directly because hasBackground() would return false for background:none.
4553 //But we still don't want the default drawning in that case (example for QScrollBar::add-page) (task 198926)
4554 subRule.drawRule(p, opt->rect);
4555 } else if (fallback) {
4556 QWindowsStyle::drawControl(ce, opt, p, w);
4557 pe2 = PseudoElement_None;
4558 } else {
4559 baseStyle()->drawControl(ce, opt, p, w);
4560 }
4561 if (pe2 != PseudoElement_None) {
4562 QRenderRule subSubRule = renderRule(w, opt, pe2);
4563 QRect r = positionRect(w, subRule, subSubRule, pe2, opt->rect, opt->direction);
4564 subSubRule.drawRule(p, r);
4565 }
4566 return;
4567 }
4568
4569 baseStyle()->drawControl(ce, opt, p, w);
4570}
4571
4572void QStyleSheetStyle::drawItemPixmap(QPainter *p, const QRect &rect, int alignment, const
4573 QPixmap &pixmap) const
4574{
4575 baseStyle()->drawItemPixmap(p, rect, alignment, pixmap);
4576}
4577
4578void QStyleSheetStyle::drawItemText(QPainter *painter, const QRect& rect, int alignment, const QPalette &pal,
4579 bool enabled, const QString& text, QPalette::ColorRole textRole) const
4580{
4581 baseStyle()->drawItemText(painter, rect, alignment, pal, enabled, text, textRole);
4582}
4583
4584void QStyleSheetStyle::drawPrimitive(PrimitiveElement pe, const QStyleOption *opt, QPainter *p,
4585 const QWidget *w) const
4586{
4587 RECURSION_GUARD(baseStyle()->drawPrimitive(pe, opt, p, w); return)
4588
4589 int pseudoElement = PseudoElement_None;
4590 QRenderRule rule = renderRule(w, opt);
4591 QRect rect = opt->rect;
4592
4593 switch (pe) {
4594
4595 case PE_FrameStatusBarItem: {
4596 QRenderRule subRule = renderRule(w ? w->parentWidget() : nullptr, opt, PseudoElement_Item);
4597 if (subRule.hasDrawable()) {
4598 subRule.drawRule(p, opt->rect);
4599 return;
4600 }
4601 break;
4602 }
4603
4604 case PE_IndicatorArrowDown:
4605 pseudoElement = PseudoElement_DownArrow;
4606 break;
4607
4608 case PE_IndicatorArrowUp:
4609 pseudoElement = PseudoElement_UpArrow;
4610 break;
4611
4612 case PE_IndicatorRadioButton:
4613 pseudoElement = PseudoElement_ExclusiveIndicator;
4614 break;
4615
4616 case PE_IndicatorItemViewItemCheck:
4617 pseudoElement = PseudoElement_ViewItemIndicator;
4618 break;
4619
4620 case PE_IndicatorCheckBox:
4621 pseudoElement = PseudoElement_Indicator;
4622 break;
4623
4624 case PE_IndicatorHeaderArrow:
4625 if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
4626 pseudoElement = hdr->sortIndicator == QStyleOptionHeader::SortUp
4627 ? PseudoElement_HeaderViewUpArrow
4628 : PseudoElement_HeaderViewDownArrow;
4629 }
4630 break;
4631
4632 case PE_PanelButtonTool:
4633 case PE_PanelButtonCommand:
4634#if QT_CONFIG(abstractbutton)
4635 if (qobject_cast<const QAbstractButton *>(w) && rule.hasBackground() && rule.hasNativeBorder()) {
4636 //the window style will draw the borders
4637 ParentStyle::drawPrimitive(pe, opt, p, w);
4638 if (!rule.background()->pixmap.isNull() || rule.hasImage()) {
4639 rule.drawRule(p, rule.boxRect(opt->rect, QRenderRule::Margin).adjusted(1,1,-1,-1));
4640 }
4641 return;
4642 }
4643#endif
4644 if (!rule.hasNativeBorder()) {
4645 rule.drawRule(p, rule.boxRect(opt->rect, QRenderRule::Margin));
4646 return;
4647 }
4648 break;
4649
4650 case PE_IndicatorButtonDropDown: {
4651 QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
4652 if (!subRule.hasNativeBorder()) {
4653 rule.drawBorder(p, opt->rect);
4654 return;
4655 }
4656 break;
4657 }
4658
4659 case PE_FrameDefaultButton:
4660 if (rule.hasNativeBorder()) {
4661 if (rule.baseStyleCanDraw())
4662 break;
4663 QWindowsStyle::drawPrimitive(pe, opt, p, w);
4664 }
4665 return;
4666
4667 case PE_FrameWindow:
4668 case PE_FrameDockWidget:
4669 case PE_Frame:
4670 if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
4671 if (rule.hasNativeBorder()) {
4672 QStyleOptionFrame frmOpt(*frm);
4673 rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
4674 baseStyle()->drawPrimitive(pe, &frmOpt, p, w);
4675 } else {
4676 rule.drawBorder(p, rule.borderRect(opt->rect));
4677 }
4678 }
4679 return;
4680
4681 case PE_PanelLineEdit:
4682 if (const QStyleOptionFrame *frm = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
4683 // Fall back to container widget's render rule
4684 if (w) {
4685 if (const QWidget *container = containerWidget(w); container != w) {
4686 QRenderRule containerRule = renderRule(container, opt);
4687 if (!containerRule.hasNativeBorder() || !containerRule.baseStyleCanDraw())
4688 return;
4689 rule = containerRule;
4690 }
4691 }
4692
4693 if (rule.hasNativeBorder()) {
4694 QStyleOptionFrame frmOpt(*frm);
4695 rule.configurePalette(&frmOpt.palette, QPalette::Text, QPalette::Base);
4696 frmOpt.rect = rule.borderRect(frmOpt.rect);
4697 if (rule.baseStyleCanDraw()) {
4698 rule.drawBackgroundImage(p, opt->rect);
4699 baseStyle()->drawPrimitive(pe, &frmOpt, p, w);
4700 } else {
4701 rule.drawBackground(p, opt->rect);
4702 if (frmOpt.lineWidth > 0)
4703 baseStyle()->drawPrimitive(PE_FrameLineEdit, &frmOpt, p, w);
4704 }
4705 } else {
4706 rule.drawRule(p, opt->rect);
4707 }
4708 }
4709 return;
4710
4711 case PE_Widget:
4712 if (w && !rule.hasDrawable()) {
4713 const QWidget *container = containerWidget(w);
4714 if (styleSheetCaches->autoFillDisabledWidgets.contains(container)
4715 && (container == w || !renderRule(container, opt).hasBackground())) {
4716 //we do not have a background, but we disabled the autofillbackground anyway. so fill the background now.
4717 // (this may happen if we have rules like :focus)
4718 p->fillRect(opt->rect, opt->palette.brush(w->backgroundRole()));
4719 }
4720 break;
4721 }
4722#if QT_CONFIG(scrollarea)
4723 if (const QAbstractScrollArea *sa = qobject_cast<const QAbstractScrollArea *>(w)) {
4724 const QAbstractScrollAreaPrivate *sap = sa->d_func();
4725 bool callBaseClass = true;
4726 if (rule.hasBackground()) {
4727 if (rule.baseStyleCanDraw())
4728 baseStyle()->drawPrimitive(pe, opt, p, w);
4729 else
4730 rule.drawBackground(p, opt->rect, sap->contentsOffset());
4731 callBaseClass = false;
4732 }
4733 if (rule.hasBorder()) {
4734 QRect brect = rule.borderRect(opt->rect);
4735 if (styleHint(QStyle::SH_ScrollView_FrameOnlyAroundContents, opt, w)) {
4736 QRect r = brect.adjusted(0, 0, sa->verticalScrollBar()->isVisible() ? -sa->verticalScrollBar()->width() : 0,
4737 sa->horizontalScrollBar()->isVisible() ? -sa->horizontalScrollBar()->height() : 0);
4738 brect = QStyle::visualRect(opt->direction, brect, r);
4739 }
4740 rule.drawBorder(p, brect);
4741 callBaseClass = false;
4742 }
4743 if (!callBaseClass)
4744 return;
4745 break;
4746 }
4747#endif
4748 Q_FALLTHROUGH();
4749 case PE_PanelMenu:
4750 case PE_PanelStatusBar:
4751 if (rule.hasDrawable()) {
4752 rule.drawRule(p, opt->rect);
4753 return;
4754 }
4755 break;
4756
4757 case PE_FrameMenu:
4758 if (rule.hasDrawable()) {
4759 // Drawn by PE_PanelMenu
4760 return;
4761 }
4762 break;
4763
4764 case PE_PanelMenuBar:
4765 if (rule.hasDrawable()) {
4766 // Drawn by PE_Widget
4767 return;
4768 }
4769 break;
4770
4771 case PE_IndicatorToolBarSeparator:
4772 case PE_IndicatorToolBarHandle: {
4773 PseudoElement ps = pe == PE_IndicatorToolBarHandle ? PseudoElement_ToolBarHandle : PseudoElement_ToolBarSeparator;
4774 QRenderRule subRule = renderRule(w, opt, ps);
4775 if (subRule.hasDrawable()) {
4776 subRule.drawRule(p, opt->rect);
4777 return;
4778 }
4779 }
4780 break;
4781
4782 case PE_IndicatorMenuCheckMark:
4783 pseudoElement = PseudoElement_MenuCheckMark;
4784 break;
4785
4786 case PE_IndicatorArrowLeft:
4787 pseudoElement = PseudoElement_LeftArrow;
4788 break;
4789
4790 case PE_IndicatorArrowRight:
4791 pseudoElement = PseudoElement_RightArrow;
4792 break;
4793
4794 case PE_IndicatorColumnViewArrow:
4795#if QT_CONFIG(itemviews)
4796 if (const QStyleOptionViewItem *viewOpt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
4797 bool reverse = (viewOpt->direction == Qt::RightToLeft);
4798 pseudoElement = reverse ? PseudoElement_LeftArrow : PseudoElement_RightArrow;
4799 } else
4800#endif
4801 {
4802 pseudoElement = PseudoElement_RightArrow;
4803 }
4804 break;
4805
4806#if QT_CONFIG(itemviews)
4807 case PE_IndicatorBranch:
4808 if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
4809 QRenderRule subRule = renderRule(w, opt, PseudoElement_TreeViewBranch);
4810 if (subRule.hasDrawable()) {
4811 proxy()->drawPrimitive(PE_PanelItemViewRow, vopt, p, w);
4812 subRule.drawRule(p, opt->rect);
4813 } else {
4814 baseStyle()->drawPrimitive(pe, vopt, p, w);
4815 }
4816 }
4817 return;
4818#endif // QT_CONFIG(itemviews)
4819
4820 case PE_PanelTipLabel:
4821 if (!rule.hasDrawable())
4822 break;
4823
4824 if (const QStyleOptionFrame *frmOpt = qstyleoption_cast<const QStyleOptionFrame *>(opt)) {
4825 if (rule.hasNativeBorder()) {
4826 rule.drawBackground(p, opt->rect);
4827 QStyleOptionFrame optCopy(*frmOpt);
4828 optCopy.rect = rule.borderRect(opt->rect);
4829 optCopy.palette.setBrush(QPalette::Window, Qt::NoBrush); // oh dear
4830 baseStyle()->drawPrimitive(pe, &optCopy, p, w);
4831 } else {
4832 rule.drawRule(p, opt->rect);
4833 }
4834 }
4835 return;
4836
4837 case PE_FrameGroupBox:
4838 if (rule.hasNativeBorder())
4839 break;
4840 rule.drawBorder(p, opt->rect);
4841 return;
4842
4843#if QT_CONFIG(tabwidget)
4844 case PE_FrameTabWidget:
4845 if (const QStyleOptionTabWidgetFrame *frm = qstyleoption_cast<const QStyleOptionTabWidgetFrame *>(opt)) {
4846 QRenderRule subRule = renderRule(w, opt, PseudoElement_TabWidgetPane);
4847 if (subRule.hasNativeBorder()) {
4848 subRule.drawBackground(p, opt->rect);
4849 QStyleOptionTabWidgetFrame frmCopy(*frm);
4850 subRule.configurePalette(&frmCopy.palette, QPalette::WindowText, QPalette::Window);
4851 baseStyle()->drawPrimitive(pe, &frmCopy, p, w);
4852 } else {
4853 subRule.drawRule(p, opt->rect);
4854 }
4855 return;
4856 }
4857 break;
4858#endif // QT_CONFIG(tabwidget)
4859
4860 case PE_IndicatorProgressChunk:
4861 pseudoElement = PseudoElement_ProgressBarChunk;
4862 break;
4863
4864 case PE_IndicatorTabTear:
4865 pseudoElement = PseudoElement_TabBarTear;
4866 break;
4867
4868 case PE_FrameFocusRect:
4869 if (!rule.hasNativeOutline()) {
4870 rule.drawOutline(p, opt->rect);
4871 return;
4872 }
4873 break;
4874
4875 case PE_IndicatorDockWidgetResizeHandle:
4876 pseudoElement = PseudoElement_DockWidgetSeparator;
4877 break;
4878
4879 case PE_PanelItemViewRow:
4880 // For compatibility reasons, QTreeView draws different parts of
4881 // the background of an item row separately, before calling the
4882 // delegate to draw the item. The row background of an item is
4883 // however not separately styleable through a style sheet, but
4884 // only indirectly through the background of the item. To get the
4885 // same background for all parts drawn by QTreeView, we have to
4886 // use the background rule for the item here.
4887 if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
4888 // default handling for drawing empty space
4889 if (vopt->viewItemPosition == QStyleOptionViewItem::Invalid)
4890 break;
4891 if (QRenderRule rule = renderRule(w, opt, PseudoElement_ViewItem); rule.hasBackground()) {
4892 // if the item background is not fully opaque, then we have to paint the row
4893 if (rule.background()->brush.color().alpha() != 1.0)
4894 baseStyle()->drawPrimitive(pe, opt, p, w);
4895 // Skip border for the branch and draw only the brackground
4896 if (vopt->features & QStyleOptionViewItem::IsDecorationForRootColumn &&
4897 (vopt->viewItemPosition == QStyleOptionViewItem::Beginning ||
4898 vopt->viewItemPosition == QStyleOptionViewItem::OnlyOne) && rule.hasBorder()) {
4899 if (rule.hasDrawable()) {
4900 rule.drawBackground(p, rect);
4901 rule.drawImage(p, rule.contentsRect(rect));
4902 } else {
4903 baseStyle()->drawPrimitive(pe, opt, p, w);
4904 }
4905 return;
4906 }
4907 pseudoElement = PseudoElement_ViewItem;
4908 }
4909 }
4910 break;
4911 case PE_PanelItemViewItem:
4912 pseudoElement = PseudoElement_ViewItem;
4913 break;
4914
4915 case PE_PanelScrollAreaCorner:
4916 pseudoElement = PseudoElement_ScrollAreaCorner;
4917 break;
4918
4919 case PE_IndicatorSpinDown:
4920 case PE_IndicatorSpinMinus:
4921 pseudoElement = PseudoElement_SpinBoxDownArrow;
4922 break;
4923
4924 case PE_IndicatorSpinUp:
4925 case PE_IndicatorSpinPlus:
4926 pseudoElement = PseudoElement_SpinBoxUpArrow;
4927 break;
4928#if QT_CONFIG(tabbar)
4929 case PE_IndicatorTabClose:
4930 if (w) {
4931 // QMacStyle needs a real widget, not its parent - to implement
4932 // 'document mode' properly, drawing nothing if a tab is not hovered.
4933 baseStyle()->setProperty("_q_styleSheetRealCloseButton", QVariant::fromValue((void *)w));
4934 w = w->parentWidget(); //match on the QTabBar instead of the CloseButton
4935 }
4936 pseudoElement = PseudoElement_TabBarTabCloseButton;
4937 break;
4938#endif
4939
4940 default:
4941 break;
4942 }
4943
4944 if (pseudoElement != PseudoElement_None) {
4945 QRenderRule subRule = renderRule(w, opt, pseudoElement);
4946 if (subRule.hasDrawable()) {
4947 subRule.drawRule(p, rect);
4948 } else {
4949 baseStyle()->drawPrimitive(pe, opt, p, w);
4950 }
4951 } else {
4952 baseStyle()->drawPrimitive(pe, opt, p, w);
4953 }
4954
4955 if (baseStyle()->property("_q_styleSheetRealCloseButton").toBool())
4956 baseStyle()->setProperty("_q_styleSheetRealCloseButton", QVariant());
4957}
4958
4959QPixmap QStyleSheetStyle::generatedIconPixmap(QIcon::Mode iconMode, const QPixmap& pixmap,
4960 const QStyleOption *option) const
4961{
4962 return baseStyle()->generatedIconPixmap(iconMode, pixmap, option);
4963}
4964
4965QStyle::SubControl QStyleSheetStyle::hitTestComplexControl(ComplexControl cc, const QStyleOptionComplex *opt,
4966 const QPoint &pt, const QWidget *w) const
4967{
4968 RECURSION_GUARD(return baseStyle()->hitTestComplexControl(cc, opt, pt, w))
4969 switch (cc) {
4970 case CC_TitleBar:
4971 if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
4972 QRenderRule rule = renderRule(w, opt, PseudoElement_TitleBar);
4973 if (rule.hasDrawable() || rule.hasBox() || rule.hasBorder()) {
4974 QHash<QStyle::SubControl, QRect> layout = titleBarLayout(w, tb);
4975 QRect r;
4976 QStyle::SubControl sc = QStyle::SC_None;
4977 uint ctrl = SC_TitleBarSysMenu;
4978 while (ctrl <= SC_TitleBarLabel) {
4979 r = layout[QStyle::SubControl(ctrl)];
4980 if (r.isValid() && r.contains(pt)) {
4981 sc = QStyle::SubControl(ctrl);
4982 break;
4983 }
4984 ctrl <<= 1;
4985 }
4986 return sc;
4987 }
4988 }
4989 break;
4990
4991 case CC_MdiControls:
4992 if (hasStyleRule(w, PseudoElement_MdiCloseButton)
4993 || hasStyleRule(w, PseudoElement_MdiNormalButton)
4994 || hasStyleRule(w, PseudoElement_MdiMinButton))
4995 return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
4996 break;
4997
4998 case CC_ScrollBar: {
4999 QRenderRule rule = renderRule(w, opt);
5000 if (!rule.hasDrawable() && !rule.hasBox())
5001 break;
5002 }
5003 Q_FALLTHROUGH();
5004 case CC_SpinBox:
5005 case CC_GroupBox:
5006 case CC_ComboBox:
5007 case CC_Slider:
5008 case CC_ToolButton:
5009 return QWindowsStyle::hitTestComplexControl(cc, opt, pt, w);
5010 default:
5011 break;
5012 }
5013
5014 return baseStyle()->hitTestComplexControl(cc, opt, pt, w);
5015}
5016
5017QRect QStyleSheetStyle::itemPixmapRect(const QRect &rect, int alignment, const QPixmap &pixmap) const
5018{
5019 return baseStyle()->itemPixmapRect(rect, alignment, pixmap);
5020}
5021
5022QRect QStyleSheetStyle::itemTextRect(const QFontMetrics &metrics, const QRect& rect, int alignment,
5023 bool enabled, const QString& text) const
5024{
5025 return baseStyle()->itemTextRect(metrics, rect, alignment, enabled, text);
5026}
5027
5028int QStyleSheetStyle::pixelMetric(PixelMetric m, const QStyleOption *opt, const QWidget *w) const
5029{
5030 RECURSION_GUARD(return baseStyle()->pixelMetric(m, opt, w))
5031
5032 QRenderRule rule = renderRule(w, opt);
5033 QRenderRule subRule;
5034
5035 switch (m) {
5036 case PM_MenuButtonIndicator:
5037#if QT_CONFIG(toolbutton)
5038 // QToolButton adds this directly to the width
5039 if (qobject_cast<const QToolButton *>(w)) {
5040 if (rule.hasBox() || !rule.hasNativeBorder())
5041 return 0;
5042 if (const auto *tbOpt = qstyleoption_cast<const QStyleOptionToolButton*>(opt)) {
5043 if (tbOpt->features & QStyleOptionToolButton::MenuButtonPopup)
5044 subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
5045 else
5046 subRule = renderRule(w, opt, PseudoElement_ToolButtonMenuIndicator);
5047 if (subRule.hasContentsSize())
5048 return subRule.size().width();
5049 }
5050 break;
5051 }
5052#endif
5053 subRule = renderRule(w, opt, PseudoElement_PushButtonMenuIndicator);
5054 if (subRule.hasContentsSize())
5055 return subRule.size().width();
5056 break;
5057
5058 case PM_ButtonShiftHorizontal:
5059 case PM_ButtonShiftVertical:
5060 case PM_ButtonMargin:
5061 case PM_ButtonDefaultIndicator:
5062 if (rule.hasBox())
5063 return 0;
5064 break;
5065
5066 case PM_DefaultFrameWidth:
5067 if (!rule.hasNativeBorder())
5068 return rule.border()->borders[LeftEdge];
5069 break;
5070
5071 case PM_ExclusiveIndicatorWidth:
5072 case PM_IndicatorWidth:
5073 case PM_ExclusiveIndicatorHeight:
5074 case PM_IndicatorHeight:
5075 subRule = renderRule(w, opt, PseudoElement_Indicator);
5076 if (subRule.hasContentsSize()) {
5077 return (m == PM_ExclusiveIndicatorWidth) || (m == PM_IndicatorWidth)
5078 ? subRule.size().width() : subRule.size().height();
5079 }
5080 break;
5081
5082 case PM_DockWidgetFrameWidth:
5083 case PM_ToolTipLabelFrameWidth: // border + margin + padding (support only one width)
5084 if (!rule.hasDrawable())
5085 break;
5086
5087 return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
5088 + (rule.hasBox() ? rule.box()->margins[LeftEdge] + rule.box()->paddings[LeftEdge]: 0);
5089
5090 case PM_ToolBarFrameWidth:
5091 if (rule.hasBorder() || rule.hasBox())
5092 return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
5093 + (rule.hasBox() ? rule.box()->paddings[LeftEdge]: 0);
5094 break;
5095
5096 case PM_MenuPanelWidth:
5097 case PM_MenuBarPanelWidth:
5098 if (rule.hasBorder() || rule.hasBox())
5099 return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
5100 + (rule.hasBox() ? rule.box()->margins[LeftEdge]: 0);
5101 break;
5102
5103
5104 case PM_MenuHMargin:
5105 case PM_MenuBarHMargin:
5106 if (rule.hasBox())
5107 return rule.box()->paddings[LeftEdge];
5108 break;
5109
5110 case PM_MenuVMargin:
5111 case PM_MenuBarVMargin:
5112 if (rule.hasBox())
5113 return rule.box()->paddings[TopEdge];
5114 break;
5115
5116 case PM_DockWidgetTitleBarButtonMargin:
5117 case PM_ToolBarItemMargin:
5118 if (rule.hasBox())
5119 return rule.box()->margins[TopEdge];
5120 break;
5121
5122 case PM_ToolBarItemSpacing:
5123 case PM_MenuBarItemSpacing:
5124 if (rule.hasBox() && rule.box()->spacing != -1)
5125 return rule.box()->spacing;
5126 break;
5127
5128 case PM_MenuTearoffHeight:
5129 case PM_MenuScrollerHeight: {
5130 PseudoElement ps = m == PM_MenuTearoffHeight ? PseudoElement_MenuTearoff : PseudoElement_MenuScroller;
5131 subRule = renderRule(w, opt, ps);
5132 if (subRule.hasContentsSize())
5133 return subRule.size().height();
5134 break;
5135 }
5136
5137 case PM_ToolBarExtensionExtent:
5138 break;
5139
5140 case PM_SplitterWidth:
5141 case PM_ToolBarSeparatorExtent:
5142 case PM_ToolBarHandleExtent: {
5143 PseudoElement ps;
5144 if (m == PM_ToolBarHandleExtent) ps = PseudoElement_ToolBarHandle;
5145 else if (m == PM_SplitterWidth) ps = PseudoElement_SplitterHandle;
5146 else ps = PseudoElement_ToolBarSeparator;
5147 subRule = renderRule(w, opt, ps);
5148 if (subRule.hasContentsSize()) {
5149 QSize sz = subRule.size();
5150 return (opt && opt->state & QStyle::State_Horizontal) ? sz.width() : sz.height();
5151 }
5152 break;
5153 }
5154
5155 case PM_RadioButtonLabelSpacing:
5156 if (rule.hasBox() && rule.box()->spacing != -1)
5157 return rule.box()->spacing;
5158 break;
5159 case PM_CheckBoxLabelSpacing:
5160#if QT_CONFIG(checkbox)
5161 if (qobject_cast<const QCheckBox *>(w)) {
5162 if (rule.hasBox() && rule.box()->spacing != -1)
5163 return rule.box()->spacing;
5164 }
5165#endif
5166 // assume group box
5167 subRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
5168 if (subRule.hasBox() && subRule.box()->spacing != -1)
5169 return subRule.box()->spacing;
5170 break;
5171
5172#if QT_CONFIG(scrollbar)
5173 case PM_ScrollBarExtent:
5174 if (rule.hasContentsSize()) {
5175 QSize sz = rule.size();
5176 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt))
5177 return sb->orientation == Qt::Horizontal ? sz.height() : sz.width();
5178 return sz.width() == -1 ? sz.height() : sz.width();
5179 }
5180 break;
5181
5182 case PM_ScrollBarSliderMin:
5183 if (hasStyleRule(w, PseudoElement_ScrollBarSlider)) {
5184 subRule = renderRule(w, opt, PseudoElement_ScrollBarSlider);
5185 QSize msz = subRule.minimumSize();
5186 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt))
5187 return sb->orientation == Qt::Horizontal ? msz.width() : msz.height();
5188 return msz.width() == -1 ? msz.height() : msz.width();
5189 }
5190 break;
5191
5192 case PM_ScrollView_ScrollBarSpacing:
5193 if (!rule.hasNativeBorder() || rule.hasBox())
5194 return 0;
5195 break;
5196
5197 case PM_ScrollView_ScrollBarOverlap:
5198 if (!proxy()->styleHint(SH_ScrollBar_Transient, opt, w))
5199 return 0;
5200 break;
5201#endif // QT_CONFIG(scrollbar)
5202
5203
5204 case PM_ProgressBarChunkWidth:
5205 subRule = renderRule(w, opt, PseudoElement_ProgressBarChunk);
5206 if (subRule.hasContentsSize()) {
5207 QSize sz = subRule.size();
5208 return (opt->state & QStyle::State_Horizontal)
5209 ? sz.width() : sz.height();
5210 }
5211 break;
5212
5213#if QT_CONFIG(tabwidget)
5214 case PM_TabBarTabHSpace:
5215 case PM_TabBarTabVSpace:
5216 subRule = renderRule(w, opt, PseudoElement_TabBarTab);
5217 if (subRule.hasBox() || subRule.hasBorder())
5218 return 0;
5219 break;
5220
5221 case PM_TabBarScrollButtonWidth:
5222 subRule = renderRule(w, opt, PseudoElement_TabBarScroller);
5223 if (subRule.hasContentsSize()) {
5224 QSize sz = subRule.size();
5225 return (sz.width() != -1 ? sz.width() : sz.height()) / 2;
5226 }
5227 break;
5228
5229 case PM_TabBarTabShiftHorizontal:
5230 case PM_TabBarTabShiftVertical:
5231 subRule = renderRule(w, opt, PseudoElement_TabBarTab);
5232 if (subRule.hasBox())
5233 return 0;
5234 break;
5235
5236 case PM_TabBarBaseOverlap: {
5237 const QWidget *tabWidget = qobject_cast<const QTabWidget *>(w);
5238 if (!tabWidget && w)
5239 tabWidget = w->parentWidget();
5240 if (hasStyleRule(tabWidget, PseudoElement_TabWidgetPane)) {
5241 return 0;
5242 }
5243 break;
5244 }
5245#endif // QT_CONFIG(tabwidget)
5246
5247 case PM_SliderThickness: // horizontal slider's height (sizeHint)
5248 case PM_SliderLength: // minimum length of slider
5249 if (rule.hasContentsSize()) {
5250 bool horizontal = opt->state & QStyle::State_Horizontal;
5251 if (m == PM_SliderThickness) {
5252 QSize sz = rule.size();
5253 return horizontal ? sz.height() : sz.width();
5254 } else {
5255 QSize msz = rule.minimumContentsSize();
5256 return horizontal ? msz.width() : msz.height();
5257 }
5258 }
5259 break;
5260
5261 case PM_SliderControlThickness: {
5262 QRenderRule subRule = renderRule(w, opt, PseudoElement_SliderHandle);
5263 if (!subRule.hasContentsSize())
5264 break;
5265 QSize size = subRule.size();
5266 return (opt->state & QStyle::State_Horizontal) ? size.height() : size.width();
5267 }
5268
5269 case PM_ToolBarIconSize:
5270 case PM_ListViewIconSize:
5271 case PM_IconViewIconSize:
5272 case PM_TabBarIconSize:
5273 case PM_MessageBoxIconSize:
5274 case PM_ButtonIconSize:
5275 case PM_SmallIconSize: {
5276 const auto styleHint = rule.styleHint("icon-size"_L1);
5277 if (styleHint.isValid() && styleHint.canConvert<QSize>())
5278 return styleHint.toSize().width();
5279 break;
5280 }
5281 case PM_DockWidgetTitleMargin: {
5282 QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
5283 if (!subRule.hasBox())
5284 break;
5285 return (subRule.border() ? subRule.border()->borders[TopEdge] : 0)
5286 + (subRule.hasBox() ? subRule.box()->margins[TopEdge] + subRule.box()->paddings[TopEdge]: 0);
5287 }
5288
5289 case PM_DockWidgetSeparatorExtent: {
5290 QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetSeparator);
5291 if (!subRule.hasContentsSize())
5292 break;
5293 QSize sz = subRule.size();
5294 return qMax(sz.width(), sz.height());
5295 }
5296
5297 case PM_TitleBarHeight: {
5298 QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
5299 if (subRule.hasContentsSize())
5300 return subRule.size().height();
5301 else if (subRule.hasBox() || subRule.hasBorder()) {
5302 QFontMetrics fm = opt ? opt->fontMetrics : w->fontMetrics();
5303 return subRule.size(QSize(0, fm.height())).height();
5304 }
5305 break;
5306 }
5307
5308 case PM_MdiSubWindowFrameWidth:
5309 if (rule.hasBox() || rule.hasBorder()) {
5310 return (rule.border() ? rule.border()->borders[LeftEdge] : 0)
5311 + (rule.hasBox() ? rule.box()->paddings[LeftEdge]+rule.box()->margins[LeftEdge]: 0);
5312 }
5313 break;
5314
5315 case PM_MdiSubWindowMinimizedWidth: {
5316 QRenderRule subRule = renderRule(w, PseudoElement_None, PseudoClass_Minimized);
5317 int width = subRule.size().width();
5318 if (width != -1)
5319 return width;
5320 break;
5321 }
5322 default:
5323 break;
5324 }
5325
5326 return baseStyle()->pixelMetric(m, opt, w);
5327}
5328
5329QSize QStyleSheetStyle::sizeFromContents(ContentsType ct, const QStyleOption *opt,
5330 const QSize &csz, const QWidget *w) const
5331{
5332 RECURSION_GUARD(return baseStyle()->sizeFromContents(ct, opt, csz, w))
5333
5334 QRenderRule rule = renderRule(w, opt);
5335 QSize sz = rule.adjustSize(csz);
5336
5337 switch (ct) {
5338#if QT_CONFIG(spinbox)
5339 case CT_SpinBox:
5340 if (const QStyleOptionSpinBox *spinbox = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
5341 if (rule.baseStyleCanDraw())
5342 sz = baseStyle()->sizeFromContents(ct, opt, sz, w);
5343 if (spinbox->buttonSymbols != QAbstractSpinBox::NoButtons) {
5344 // Add some space for the up/down buttons
5345 QRenderRule subRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
5346 if (subRule.hasDrawable()) {
5347 QRect r = positionRect(w, rule, subRule, PseudoElement_SpinBoxUpButton,
5348 opt->rect, opt->direction);
5349 sz.rwidth() += r.width();
5350 } else if (!rule.baseStyleCanDraw()) {
5351 // Otherwise the base style's hint already accounts for the buttons.
5352 QSize defaultUpSize = defaultSize(w, subRule.size(), spinbox->rect, PseudoElement_SpinBoxUpButton);
5353 sz.rwidth() += defaultUpSize.width();
5354 }
5355 }
5356 const bool honorBorder = !rule.baseStyleCanDraw() && rule.hasBorder();
5357 if (rule.hasBox() || honorBorder || !rule.hasNativeBorder())
5358 sz = rule.boxSize(sz);
5359 return sz;
5360 }
5361 break;
5362#endif // QT_CONFIG(spinbox)
5363 case CT_ToolButton:
5364 if (rule.hasBox() || !rule.hasNativeBorder() || !rule.baseStyleCanDraw())
5365 sz += QSize(3, 3); // ### broken QToolButton
5366 Q_FALLTHROUGH();
5367 case CT_ComboBox:
5368 case CT_PushButton:
5369 if (rule.hasBox() || !rule.hasNativeBorder()) {
5370 if (ct == CT_ComboBox) {
5371 //add some space for the drop down.
5372 QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
5373 QRect comboRect = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
5374 //+2 because there is hardcoded margins in QCommonStyle::drawControl(CE_ComboBoxLabel)
5375 sz += QSize(comboRect.width() + 2, 0);
5376 }
5377 return rule.boxSize(sz);
5378 }
5379 sz = rule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
5380 : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
5381 return rule.boxSize(sz, Margin);
5382
5383 case CT_HeaderSection: {
5384 if (const QStyleOptionHeader *hdr = qstyleoption_cast<const QStyleOptionHeader *>(opt)) {
5385 QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
5386 if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
5387 sz = subRule.adjustSize(csz);
5388 if (!sz.isValid()) {
5389 // Try to set the missing values based on the base style.
5390 const auto baseSize = baseStyle()->sizeFromContents(ct, opt, sz, w);
5391 if (sz.width() < 0)
5392 sz.setWidth(baseSize.width());
5393 if (sz.height() < 0)
5394 sz.setHeight(baseSize.height());
5395 }
5396 if (!subRule.hasGeometry()) {
5397 QSize nativeContentsSize;
5398 bool nullIcon = hdr->icon.isNull();
5399 const int margin = pixelMetric(QStyle::PM_HeaderMargin, hdr, w);
5400 int iconSize = nullIcon ? 0 : pixelMetric(QStyle::PM_SmallIconSize, hdr, w);
5401 QFontMetrics fm = hdr->fontMetrics;
5402 if (subRule.hasFont) {
5403 QFont styleFont = w ? subRule.font.resolve(w->font()) : subRule.font;
5404 fm = QFontMetrics(styleFont);
5405 }
5406 const QSize txt = fm.size(0, hdr->text);
5407 nativeContentsSize.setHeight(margin + qMax(iconSize, txt.height()) + margin);
5408 nativeContentsSize.setWidth((nullIcon ? 0 : margin) + iconSize
5409 + (hdr->text.isNull() ? 0 : margin) + txt.width() + margin);
5410 sz = sz.expandedTo(nativeContentsSize);
5411 }
5412 return subRule.size(sz);
5413 }
5414 return subRule.baseStyleCanDraw() ? baseStyle()->sizeFromContents(ct, opt, sz, w)
5415 : QWindowsStyle::sizeFromContents(ct, opt, sz, w);
5416 }
5417 }
5418 break;
5419 case CT_GroupBox:
5420 case CT_LineEdit:
5421#if QT_CONFIG(spinbox)
5422 if (auto *spinBox = qobject_cast<QAbstractSpinBox *>(w ? w->parentWidget() : nullptr)) {
5423 // If the spin box draws its own frame (custom box or non-native border),
5424 // return the contents size; otherwise defer to the base style so the line
5425 // edit still contributes its natural frame.
5426 const QRenderRule spinBoxRule = renderRule(spinBox, opt);
5427 if (spinBoxRule.hasBox() || !spinBoxRule.hasNativeBorder())
5428 return csz;
5429 return baseStyle()->sizeFromContents(ct, opt, sz, w);
5430 }
5431#endif
5432 if (rule.hasBox() || !rule.hasNativeBorder()) {
5433 return rule.boxSize(sz);
5434 }
5435 break;
5436
5437 case CT_CheckBox:
5438 case CT_RadioButton:
5439 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
5440 if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
5441 bool isRadio = (ct == CT_RadioButton);
5442 int iw = pixelMetric(isRadio ? PM_ExclusiveIndicatorWidth
5443 : PM_IndicatorWidth, btn, w);
5444 int ih = pixelMetric(isRadio ? PM_ExclusiveIndicatorHeight
5445 : PM_IndicatorHeight, btn, w);
5446
5447 int spacing = pixelMetric(isRadio ? PM_RadioButtonLabelSpacing
5448 : PM_CheckBoxLabelSpacing, btn, w);
5449 sz.setWidth(sz.width() + iw + spacing);
5450 sz.setHeight(qMax(sz.height(), ih));
5451 return rule.boxSize(sz);
5452 }
5453 }
5454 break;
5455
5456 case CT_Menu:
5457 case CT_MenuBar: // already has everything!
5458 case CT_ScrollBar:
5459 if (rule.hasBox() || rule.hasBorder())
5460 return sz;
5461 break;
5462
5463 case CT_MenuItem:
5464 if (const QStyleOptionMenuItem *mi = qstyleoption_cast<const QStyleOptionMenuItem *>(opt)) {
5465 PseudoElement pe = (mi->menuItemType == QStyleOptionMenuItem::Separator)
5466 ? PseudoElement_MenuSeparator : PseudoElement_Item;
5467 QRenderRule subRule = renderRule(w, opt, pe);
5468 if ((pe == PseudoElement_MenuSeparator) && subRule.hasContentsSize()) {
5469 return QSize(sz.width(), subRule.size().height());
5470 }
5471 if ((pe == PseudoElement_Item) && (subRule.hasBox() || subRule.hasBorder() || subRule.hasFont)) {
5472 bool drawCheckMark = mi->menuHasCheckableItems;
5473#if QT_CONFIG(combobox)
5474 if (qobject_cast<const QComboBox *>(w))
5475 drawCheckMark = false; // ignore the checkmarks provided by the QComboMenuDelegate
5476#endif
5477 QSize sz(csz);
5478 if (subRule.hasFont) {
5479 QFontMetrics fm(subRule.font.resolve(mi->font));
5480 const QRect r = fm.boundingRect(QRect(), Qt::TextSingleLine | Qt::TextShowMnemonic, mi->text);
5481 sz = sz.expandedTo(r.size());
5482 }
5483 if (mi->text.contains(u'\t'))
5484 sz.rwidth() += 12; //as in QCommonStyle
5485 if (!mi->icon.isNull()) {
5486 const int pmSmall = pixelMetric(PM_SmallIconSize);
5487 const QSize pmSize = mi->icon.actualSize(QSize(pmSmall, pmSmall));
5488 sz.rwidth() += std::max(mi->maxIconWidth, pmSize.width()) + 4;
5489 } else if (drawCheckMark) {
5490 QRenderRule subSubRule = renderRule(w, opt, PseudoElement_MenuCheckMark);
5491 QRect checkmarkRect = positionRect(w, subRule, subSubRule, PseudoElement_MenuCheckMark, opt->rect, opt->direction);
5492 sz.rwidth() += std::max(mi->maxIconWidth, checkmarkRect.width()) + 4;
5493 } else {
5494 sz.rwidth() += mi->maxIconWidth;
5495 }
5496 return subRule.boxSize(subRule.adjustSize(sz));
5497 }
5498 }
5499 break;
5500
5501 case CT_Splitter:
5502 case CT_MenuBarItem: {
5503 PseudoElement pe = (ct == CT_Splitter) ? PseudoElement_SplitterHandle : PseudoElement_Item;
5504 QRenderRule subRule = renderRule(w, opt, pe);
5505 if (subRule.hasBox() || subRule.hasBorder())
5506 return subRule.boxSize(sz);
5507 break;
5508 }
5509
5510 case CT_ProgressBar:
5511 case CT_SizeGrip:
5512 return (rule.hasContentsSize())
5513 ? rule.size(sz)
5514 : rule.boxSize(baseStyle()->sizeFromContents(ct, opt, sz, w));
5515 break;
5516
5517 case CT_Slider:
5518 if (rule.hasBorder() || rule.hasBox() || rule.hasGeometry())
5519 return rule.boxSize(sz);
5520 break;
5521
5522#if QT_CONFIG(tabbar)
5523 case CT_TabBarTab: {
5524 QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
5525 if (subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
5526 int spaceForIcon = 0;
5527 bool vertical = false;
5528 QString text;
5529 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
5530 if (!tab->icon.isNull())
5531 spaceForIcon = 6 /* icon offset */ + 4 /* spacing */ + 2 /* magic */; // ###: hardcoded to match with common style
5532 vertical = verticalTabs(tab->shape);
5533 text = tab->text;
5534 }
5535 if (subRule.hasBox() || !subRule.hasNativeBorder())
5536 sz = csz + QSize(vertical ? 0 : spaceForIcon, vertical ? spaceForIcon : 0);
5537 if (subRule.hasFont) {
5538 // first we remove the space needed for the text using the default font
5539 const QSize oldTextSize = opt->fontMetrics.size(Qt::TextShowMnemonic, text);
5540 (vertical ? sz.rheight() : sz.rwidth()) -= oldTextSize.width();
5541
5542 // then we add the space needed when using the rule font to the relevant
5543 // dimension, and constraint the other dimension to the maximum to make
5544 // sure we don't grow, but also don't clip icons or buttons.
5545 const QFont ruleFont = subRule.font.resolve(w->font());
5546 const QFontMetrics fm(ruleFont);
5547 const QSize textSize = fm.size(Qt::TextShowMnemonic, text);
5548 if (vertical) {
5549 sz.rheight() += textSize.width();
5550 sz.rwidth() = qMax(textSize.height(), sz.width());
5551 } else {
5552 sz.rwidth() += textSize.width();
5553 sz.rheight() = qMax(textSize.height(), sz.height());
5554 }
5555 }
5556
5557 return subRule.boxSize(subRule.adjustSize(sz));
5558 }
5559 sz = subRule.adjustSize(csz);
5560 break;
5561 }
5562#endif // QT_CONFIG(tabbar)
5563
5564 case CT_MdiControls:
5565 if (const QStyleOptionComplex *ccOpt = qstyleoption_cast<const QStyleOptionComplex *>(opt)) {
5566 if (!hasStyleRule(w, PseudoElement_MdiCloseButton)
5567 && !hasStyleRule(w, PseudoElement_MdiNormalButton)
5568 && !hasStyleRule(w, PseudoElement_MdiMinButton))
5569 break;
5570
5571 QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
5572 if (layout.isEmpty())
5573 layout = subControlLayout("mNX");
5574
5575 int width = 0, height = 0;
5576 for (const QVariant &val : std::as_const(layout)) {
5577 int layoutButton = val.toInt();
5578 if (layoutButton < PseudoElement_MdiCloseButton
5579 || layoutButton > PseudoElement_MdiNormalButton)
5580 continue;
5581 QStyle::SubControl sc = knownPseudoElements[layoutButton].subControl;
5582 if (!(ccOpt->subControls & sc))
5583 continue;
5584 QRenderRule subRule = renderRule(w, opt, layoutButton);
5585 QSize sz = subRule.size();
5586 width += sz.width();
5587 height = qMax(height, sz.height());
5588 }
5589
5590 return QSize(width, height);
5591 }
5592 break;
5593
5594#if QT_CONFIG(itemviews)
5595 case CT_ItemViewItem: {
5596 QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
5597 sz = baseStyle()->sizeFromContents(ct, opt, csz, w);
5598 sz = subRule.adjustSize(sz);
5599 if (subRule.hasBox() || subRule.hasBorder())
5600 sz = subRule.boxSize(sz);
5601 return sz;
5602 }
5603#endif // QT_CONFIG(itemviews)
5604
5605 default:
5606 break;
5607 }
5608
5609 return baseStyle()->sizeFromContents(ct, opt, sz, w);
5610}
5611
5612/*!
5613 \internal
5614*/
5615static QLatin1StringView propertyNameForStandardPixmap(QStyle::StandardPixmap sp)
5616{
5617 switch (sp) {
5618 case QStyle::SP_TitleBarMenuButton: return "titlebar-menu-icon"_L1;
5619 case QStyle::SP_TitleBarMinButton: return "titlebar-minimize-icon"_L1;
5620 case QStyle::SP_TitleBarMaxButton: return "titlebar-maximize-icon"_L1;
5621 case QStyle::SP_TitleBarCloseButton: return "titlebar-close-icon"_L1;
5622 case QStyle::SP_TitleBarNormalButton: return "titlebar-normal-icon"_L1;
5623 case QStyle::SP_TitleBarShadeButton: return "titlebar-shade-icon"_L1;
5624 case QStyle::SP_TitleBarUnshadeButton: return "titlebar-unshade-icon"_L1;
5625 case QStyle::SP_TitleBarContextHelpButton: return "titlebar-contexthelp-icon"_L1;
5626 case QStyle::SP_DockWidgetCloseButton: return "dockwidget-close-icon"_L1;
5627 case QStyle::SP_MessageBoxInformation: return "messagebox-information-icon"_L1;
5628 case QStyle::SP_MessageBoxWarning: return "messagebox-warning-icon"_L1;
5629 case QStyle::SP_MessageBoxCritical: return "messagebox-critical-icon"_L1;
5630 case QStyle::SP_MessageBoxQuestion: return "messagebox-question-icon"_L1;
5631 case QStyle::SP_DesktopIcon: return "desktop-icon"_L1;
5632 case QStyle::SP_TrashIcon: return "trash-icon"_L1;
5633 case QStyle::SP_ComputerIcon: return "computer-icon"_L1;
5634 case QStyle::SP_DriveFDIcon: return "floppy-icon"_L1;
5635 case QStyle::SP_DriveHDIcon: return "harddisk-icon"_L1;
5636 case QStyle::SP_DriveCDIcon: return "cd-icon"_L1;
5637 case QStyle::SP_DriveDVDIcon: return "dvd-icon"_L1;
5638 case QStyle::SP_DriveNetIcon: return "network-icon"_L1;
5639 case QStyle::SP_DirOpenIcon: return "directory-open-icon"_L1;
5640 case QStyle::SP_DirClosedIcon: return "directory-closed-icon"_L1;
5641 case QStyle::SP_DirLinkIcon: return "directory-link-icon"_L1;
5642 case QStyle::SP_FileIcon: return "file-icon"_L1;
5643 case QStyle::SP_FileLinkIcon: return "file-link-icon"_L1;
5644 case QStyle::SP_FileDialogStart: return "filedialog-start-icon"_L1;
5645 case QStyle::SP_FileDialogEnd: return "filedialog-end-icon"_L1;
5646 case QStyle::SP_FileDialogToParent: return "filedialog-parent-directory-icon"_L1;
5647 case QStyle::SP_FileDialogNewFolder: return "filedialog-new-directory-icon"_L1;
5648 case QStyle::SP_FileDialogDetailedView: return "filedialog-detailedview-icon"_L1;
5649 case QStyle::SP_FileDialogInfoView: return "filedialog-infoview-icon"_L1;
5650 case QStyle::SP_FileDialogContentsView: return "filedialog-contentsview-icon"_L1;
5651 case QStyle::SP_FileDialogListView: return "filedialog-listview-icon"_L1;
5652 case QStyle::SP_FileDialogBack: return "filedialog-backward-icon"_L1;
5653 case QStyle::SP_DirIcon: return "directory-icon"_L1;
5654 case QStyle::SP_DialogOkButton: return "dialog-ok-icon"_L1;
5655 case QStyle::SP_DialogCancelButton: return "dialog-cancel-icon"_L1;
5656 case QStyle::SP_DialogHelpButton: return "dialog-help-icon"_L1;
5657 case QStyle::SP_DialogOpenButton: return "dialog-open-icon"_L1;
5658 case QStyle::SP_DialogSaveButton: return "dialog-save-icon"_L1;
5659 case QStyle::SP_DialogCloseButton: return "dialog-close-icon"_L1;
5660 case QStyle::SP_DialogApplyButton: return "dialog-apply-icon"_L1;
5661 case QStyle::SP_DialogResetButton: return "dialog-reset-icon"_L1;
5662 case QStyle::SP_DialogDiscardButton: return "dialog-discard-icon"_L1;
5663 case QStyle::SP_DialogYesButton: return "dialog-yes-icon"_L1;
5664 case QStyle::SP_DialogNoButton: return "dialog-no-icon"_L1;
5665 case QStyle::SP_ArrowUp: return "uparrow-icon"_L1;
5666 case QStyle::SP_ArrowDown: return "downarrow-icon"_L1;
5667 case QStyle::SP_ArrowLeft: return "leftarrow-icon"_L1;
5668 case QStyle::SP_ArrowRight: return "rightarrow-icon"_L1;
5669 case QStyle::SP_ArrowBack: return "backward-icon"_L1;
5670 case QStyle::SP_ArrowForward: return "forward-icon"_L1;
5671 case QStyle::SP_DirHomeIcon: return "home-icon"_L1;
5672 case QStyle::SP_LineEditClearButton: return "lineedit-clear-button-icon"_L1;
5673 default: return ""_L1;
5674 }
5675}
5676
5677QIcon QStyleSheetStyle::standardIcon(StandardPixmap standardIcon, const QStyleOption *opt,
5678 const QWidget *w) const
5679{
5680 RECURSION_GUARD(return baseStyle()->standardIcon(standardIcon, opt, w))
5681 const auto s = propertyNameForStandardPixmap(standardIcon);
5682 if (!s.isEmpty()) {
5683 const auto styleHint = renderRule(w, opt).styleHint(s);
5684 if (styleHint.isValid() && styleHint.canConvert<QIcon>())
5685 return qvariant_cast<QIcon>(styleHint);
5686 }
5687 return baseStyle()->standardIcon(standardIcon, opt, w);
5688}
5689
5690QPalette QStyleSheetStyle::standardPalette() const
5691{
5692 return baseStyle()->standardPalette();
5693}
5694
5695QPixmap QStyleSheetStyle::standardPixmap(StandardPixmap standardPixmap, const QStyleOption *opt,
5696 const QWidget *w) const
5697{
5698 RECURSION_GUARD(return baseStyle()->standardPixmap(standardPixmap, opt, w))
5699 const auto s = propertyNameForStandardPixmap(standardPixmap);
5700 if (!s.isEmpty()) {
5701 const auto styleHint = renderRule(w, opt).styleHint(s);
5702 if (styleHint.isValid() && styleHint.canConvert<QIcon>()) {
5703 QIcon icon = qvariant_cast<QIcon>(styleHint);
5704 return icon.pixmap(QSize(16, 16), QStyleHelper::getDpr(w));
5705 }
5706 }
5707 return baseStyle()->standardPixmap(standardPixmap, opt, w);
5708}
5709
5710int QStyleSheetStyle::layoutSpacing(QSizePolicy::ControlType control1, QSizePolicy::ControlType control2,
5711 Qt::Orientation orientation, const QStyleOption *option,
5712 const QWidget *widget) const
5713{
5714 return baseStyle()->layoutSpacing(control1, control2, orientation, option, widget);
5715}
5716
5717int QStyleSheetStyle::styleHint(StyleHint sh, const QStyleOption *opt, const QWidget *w,
5718 QStyleHintReturn *shret) const
5719{
5720 RECURSION_GUARD(return baseStyle()->styleHint(sh, opt, w, shret))
5721 // Prevent endless loop if somebody use isActiveWindow property as selector.
5722 // QWidget::isActiveWindow uses this styleHint to determine if the window is active or not
5723 if (sh == SH_Widget_ShareActivation)
5724 return baseStyle()->styleHint(sh, opt, w, shret);
5725
5726 QRenderRule rule = renderRule(w, opt);
5727 QLatin1StringView s;
5728 switch (sh) {
5729 case SH_LineEdit_PasswordCharacter: s = "lineedit-password-character"_L1; break;
5730 case SH_LineEdit_PasswordMaskDelay: s = "lineedit-password-mask-delay"_L1; break;
5731 case SH_DitherDisabledText: s = "dither-disabled-text"_L1; break;
5732 case SH_EtchDisabledText: s = "etch-disabled-text"_L1; break;
5733 case SH_ItemView_ActivateItemOnSingleClick: s = "activate-on-singleclick"_L1; break;
5734 case SH_ItemView_ShowDecorationSelected: s = "show-decoration-selected"_L1; break;
5735 case SH_Table_GridLineColor: s = "gridline-color"_L1; break;
5736 case SH_DialogButtonLayout: s = "button-layout"_L1; break;
5737 case SH_ToolTipLabel_Opacity: s = "opacity"_L1; break;
5738 case SH_ComboBox_Popup: s = "combobox-popup"_L1; break;
5739 case SH_ComboBox_ListMouseTracking: s = "combobox-list-mousetracking"_L1; break;
5740 case SH_MenuBar_AltKeyNavigation: s = "menubar-altkey-navigation"_L1; break;
5741 case SH_Menu_Scrollable: s = "menu-scrollable"_L1; break;
5742 case SH_DrawMenuBarSeparator: s = "menubar-separator"_L1; break;
5743 case SH_MenuBar_MouseTracking: s = "mouse-tracking"_L1; break;
5744 case SH_SpinBox_ClickAutoRepeatRate: s = "spinbox-click-autorepeat-rate"_L1; break;
5745 case SH_SpinControls_DisableOnBounds: s = "spincontrol-disable-on-bounds"_L1; break;
5746 case SH_MessageBox_TextInteractionFlags: s = "messagebox-text-interaction-flags"_L1; break;
5747 case SH_ToolButton_PopupDelay: s = "toolbutton-popup-delay"_L1; break;
5748 case SH_ToolBox_SelectedPageTitleBold:
5749 if (renderRule(w, opt, PseudoElement_ToolBoxTab).hasFont)
5750 return 0;
5751 break;
5752 case SH_GroupBox_TextLabelColor:
5753 if (rule.hasPalette() && rule.palette()->foreground.style() != Qt::NoBrush)
5754 return rule.palette()->foreground.color().rgba();
5755 break;
5756 case SH_ScrollView_FrameOnlyAroundContents: s = "scrollview-frame-around-contents"_L1; break;
5757 case SH_ScrollBar_ContextMenu: s = "scrollbar-contextmenu"_L1; break;
5758 case SH_ScrollBar_LeftClickAbsolutePosition: s = "scrollbar-leftclick-absolute-position"_L1; break;
5759 case SH_ScrollBar_MiddleClickAbsolutePosition: s = "scrollbar-middleclick-absolute-position"_L1; break;
5760 case SH_ScrollBar_RollBetweenButtons: s = "scrollbar-roll-between-buttons"_L1; break;
5761 case SH_ScrollBar_ScrollWhenPointerLeavesControl: s = "scrollbar-scroll-when-pointer-leaves-control"_L1; break;
5762 case SH_TabBar_Alignment:
5763#if QT_CONFIG(tabwidget)
5764 if (qobject_cast<const QTabWidget *>(w)) {
5765 rule = renderRule(w, opt, PseudoElement_TabWidgetTabBar);
5766 if (rule.hasPosition())
5767 return rule.position()->position;
5768 }
5769#endif // QT_CONFIG(tabwidget)
5770 s = "alignment"_L1;
5771 break;
5772#if QT_CONFIG(tabbar)
5773 case SH_TabBar_CloseButtonPosition:
5774 rule = renderRule(w, opt, PseudoElement_TabBarTabCloseButton);
5775 if (rule.hasPosition()) {
5776 Qt::Alignment align = rule.position()->position;
5777 if (align & Qt::AlignLeft || align & Qt::AlignTop)
5778 return QTabBar::LeftSide;
5779 if (align & Qt::AlignRight || align & Qt::AlignBottom)
5780 return QTabBar::RightSide;
5781 }
5782 break;
5783#endif
5784 case SH_TabBar_ElideMode: s = "tabbar-elide-mode"_L1; break;
5785 case SH_TabBar_PreferNoArrows: s = "tabbar-prefer-no-arrows"_L1; break;
5786 case SH_ComboBox_PopupFrameStyle:
5787#if QT_CONFIG(combobox)
5788 if (qobject_cast<const QComboBox *>(w)) {
5789 QAbstractItemView *view = w->findChild<QAbstractItemView *>();
5790 if (view) {
5791 view->ensurePolished();
5792 QRenderRule subRule = renderRule(view, PseudoElement_None);
5793 if (subRule.hasBox() || !subRule.hasNativeBorder())
5794 return QFrame::NoFrame;
5795 }
5796 }
5797#endif // QT_CONFIG(combobox)
5798 break;
5799 case SH_DialogButtonBox_ButtonsHaveIcons: s = "dialogbuttonbox-buttons-have-icons"_L1; break;
5800 case SH_Workspace_FillSpaceOnMaximize: s = "mdi-fill-space-on-maximize"_L1; break;
5801 case SH_TitleBar_NoBorder:
5802 if (rule.hasBorder())
5803 return !rule.border()->borders[LeftEdge];
5804 break;
5805 case SH_TitleBar_AutoRaise: { // plain absurd
5806 QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
5807 if (subRule.hasDrawable())
5808 return 1;
5809 break;
5810 }
5811 case SH_ItemView_ArrowKeysNavigateIntoChildren: s = "arrow-keys-navigate-into-children"_L1; break;
5812 case SH_ItemView_PaintAlternatingRowColorsForEmptyArea: s = "paint-alternating-row-colors-for-empty-area"_L1; break;
5813 case SH_TitleBar_ShowToolTipsOnButtons: s = "titlebar-show-tooltips-on-buttons"_L1; break;
5814 case SH_Widget_Animation_Duration: s = "widget-animation-duration"_L1; break;
5815 case SH_ScrollBar_Transient:
5816 if (!rule.hasNativeBorder() || rule.hasBox() || rule.hasDrawable())
5817 return 0;
5818 break;
5819 default: break;
5820 }
5821 if (!s.isEmpty()) {
5822 const auto styleHint = rule.styleHint(s);
5823 if (styleHint.isValid() && styleHint.canConvert<int>())
5824 return styleHint.toInt();
5825 }
5826
5827 return baseStyle()->styleHint(sh, opt, w, shret);
5828}
5829
5830QRect QStyleSheetStyle::subControlRect(ComplexControl cc, const QStyleOptionComplex *opt, SubControl sc,
5831 const QWidget *w) const
5832{
5833 RECURSION_GUARD(return baseStyle()->subControlRect(cc, opt, sc, w))
5834
5835 QRenderRule rule = renderRule(w, opt);
5836 switch (cc) {
5837 case CC_ComboBox:
5838 if (const QStyleOptionComboBox *cb = qstyleoption_cast<const QStyleOptionComboBox *>(opt)) {
5839 if (rule.hasBox() || !rule.hasNativeBorder()) {
5840 switch (sc) {
5841 case SC_ComboBoxFrame: return rule.borderRect(opt->rect);
5842 case SC_ComboBoxEditField:
5843 {
5844 QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
5845 QRect r = rule.contentsRect(opt->rect);
5846 QRect r2 = positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown,
5847 opt->rect, opt->direction);
5848 if (subRule.hasPosition() && subRule.position()->position & Qt::AlignLeft) {
5849 return visualRect(opt->direction, r, r.adjusted(r2.width(),0,0,0));
5850 } else {
5851 return visualRect(opt->direction, r, r.adjusted(0,0,-r2.width(),0));
5852 }
5853 }
5854 case SC_ComboBoxArrow: {
5855 QRenderRule subRule = renderRule(w, opt, PseudoElement_ComboBoxDropDown);
5856 return positionRect(w, rule, subRule, PseudoElement_ComboBoxDropDown, opt->rect, opt->direction);
5857 }
5858 case SC_ComboBoxListBoxPopup:
5859 default:
5860 return baseStyle()->subControlRect(cc, opt, sc, w);
5861 }
5862 }
5863
5864 QStyleOptionComboBox comboBox(*cb);
5865 comboBox.rect = rule.borderRect(opt->rect);
5866 return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &comboBox, sc, w)
5867 : QWindowsStyle::subControlRect(cc, &comboBox, sc, w);
5868 }
5869 break;
5870
5871#if QT_CONFIG(spinbox)
5872 case CC_SpinBox:
5873 if (const QStyleOptionSpinBox *spin = qstyleoption_cast<const QStyleOptionSpinBox *>(opt)) {
5874 QRenderRule upRule = renderRule(w, opt, PseudoElement_SpinBoxUpButton);
5875 QRenderRule downRule = renderRule(w, opt, PseudoElement_SpinBoxDownButton);
5876 bool ruleMatch = rule.hasBox() || !rule.hasNativeBorder();
5877 bool upRuleMatch = upRule.hasGeometry() || upRule.hasPosition();
5878 bool downRuleMatch = downRule.hasGeometry() || downRule.hasPosition();
5879 if (ruleMatch || upRuleMatch || downRuleMatch) {
5880 switch (sc) {
5881 case SC_SpinBoxFrame:
5882 return rule.borderRect(opt->rect);
5883 case SC_SpinBoxEditField: {
5884 QRect r = rule.contentsRect(opt->rect);
5885 if (spin->buttonSymbols != QAbstractSpinBox::NoButtons) {
5886 // Use the widest button on each side to determine edit field size.
5887 Qt::Alignment upAlign =
5888 upRule.hasPosition() ? upRule.position()->position : Qt::AlignRight;
5889 upAlign = resolveAlignment(opt->direction, upAlign);
5890 upAlign &= Qt::AlignLeft | Qt::AlignRight;
5891
5892 Qt::Alignment downAlign = downRule.hasPosition()
5893 ? downRule.position()->position
5894 : Qt::AlignRight;
5895 downAlign = resolveAlignment(opt->direction, downAlign);
5896 downAlign &= Qt::AlignLeft | Qt::AlignRight;
5897
5898 const QRect upRect = subControlRect(CC_SpinBox, opt, SC_SpinBoxUp, w);
5899 const QRect downRect = subControlRect(CC_SpinBox, opt, SC_SpinBoxDown, w);
5900
5901 int widestL = 0;
5902 int widestR = 0;
5903 if (upAlign & downAlign) {
5904 // both on same side
5905 int minX = std::min(upRect.left(), downRect.left());
5906 int maxX = std::max(upRect.right(), downRect.right());
5907 if (upAlign & Qt::AlignRight)
5908 r.setRight(minX);
5909 else
5910 r.setLeft(maxX);
5911 } else {
5912 // one on the right, one on the left
5913 widestL = qMax((upAlign & Qt::AlignLeft) ? upRect.width() : 0,
5914 (downAlign & Qt::AlignLeft) ? downRect.width() : 0);
5915 widestR = qMax((upAlign & Qt::AlignRight) ? upRect.width() : 0,
5916 (downAlign & Qt::AlignRight) ? downRect.width() : 0);
5917 r.setRight(r.right() - widestR);
5918 r.setLeft(r.left() + widestL);
5919 }
5920 }
5921 return r;
5922 }
5923 case SC_SpinBoxDown:
5924 if (downRuleMatch)
5925 return positionRect(w, rule, downRule, PseudoElement_SpinBoxDownButton,
5926 opt->rect, opt->direction);
5927 break;
5928 case SC_SpinBoxUp:
5929 if (upRuleMatch)
5930 return positionRect(w, rule, upRule, PseudoElement_SpinBoxUpButton,
5931 opt->rect, opt->direction);
5932 break;
5933 default:
5934 break;
5935 }
5936
5937 return baseStyle()->subControlRect(cc, opt, sc, w);
5938 }
5939
5940 QStyleOptionSpinBox spinBox(*spin);
5941 spinBox.rect = rule.borderRect(opt->rect);
5942 return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &spinBox, sc, w)
5943 : QWindowsStyle::subControlRect(cc, &spinBox, sc, w);
5944 }
5945 break;
5946#endif // QT_CONFIG(spinbox)
5947
5948 case CC_GroupBox:
5949 if (const QStyleOptionGroupBox *gb = qstyleoption_cast<const QStyleOptionGroupBox *>(opt)) {
5950 switch (sc) {
5951 case SC_GroupBoxFrame:
5952 case SC_GroupBoxContents: {
5953 if (rule.hasBox() || !rule.hasNativeBorder()) {
5954 return sc == SC_GroupBoxFrame ? rule.borderRect(opt->rect)
5955 : rule.contentsRect(opt->rect);
5956 }
5957 QStyleOptionGroupBox groupBox(*gb);
5958 groupBox.rect = rule.borderRect(opt->rect);
5959 return baseStyle()->subControlRect(cc, &groupBox, sc, w);
5960 }
5961 default:
5962 case SC_GroupBoxLabel:
5963 case SC_GroupBoxCheckBox: {
5964 QRenderRule indRule = renderRule(w, opt, PseudoElement_GroupBoxIndicator);
5965 QRenderRule labelRule = renderRule(w, opt, PseudoElement_GroupBoxTitle);
5966 if (!labelRule.hasPosition() && !labelRule.hasGeometry() && !labelRule.hasBox()
5967 && !labelRule.hasBorder() && !indRule.hasContentsSize()) {
5968 QStyleOptionGroupBox groupBox(*gb);
5969 groupBox.rect = rule.borderRect(opt->rect);
5970 return baseStyle()->subControlRect(cc, &groupBox, sc, w);
5971 }
5972 int tw = opt->fontMetrics.horizontalAdvance(gb->text);
5973 int th = opt->fontMetrics.height();
5974 int spacing = pixelMetric(QStyle::PM_CheckBoxLabelSpacing, opt, w);
5975 int iw = pixelMetric(QStyle::PM_IndicatorWidth, opt, w);
5976 int ih = pixelMetric(QStyle::PM_IndicatorHeight, opt, w);
5977
5978 if (gb->subControls & QStyle::SC_GroupBoxCheckBox) {
5979 tw = tw + iw + spacing;
5980 th = qMax(th, ih);
5981 }
5982 if (!labelRule.hasGeometry()) {
5983 labelRule.geo = new QStyleSheetGeometryData(tw, th, tw, th, -1, -1);
5984 } else {
5985 labelRule.geo->width = tw;
5986 labelRule.geo->height = th;
5987 }
5988 if (!labelRule.hasPosition()) {
5989 labelRule.p = new QStyleSheetPositionData(0, 0, 0, 0, defaultOrigin(PseudoElement_GroupBoxTitle),
5990 gb->textAlignment, PositionMode_Static);
5991 }
5992 QRect r = positionRect(w, rule, labelRule, PseudoElement_GroupBoxTitle,
5993 opt->rect, opt->direction);
5994 if (gb->subControls & SC_GroupBoxCheckBox) {
5995 r = labelRule.contentsRect(r);
5996 if (sc == SC_GroupBoxLabel) {
5997 r.setLeft(r.left() + iw + spacing);
5998 r.setTop(r.center().y() - th/2);
5999 } else {
6000 r = QRect(r.left(), r.center().y() - ih/2, iw, ih);
6001 }
6002 return r;
6003 } else {
6004 return labelRule.contentsRect(r);
6005 }
6006 }
6007 } // switch
6008 }
6009 break;
6010
6011 case CC_ToolButton:
6012#if QT_CONFIG(toolbutton)
6013 if (const QStyleOptionToolButton *tb = qstyleoption_cast<const QStyleOptionToolButton *>(opt)) {
6014 if (rule.hasBox() || !rule.hasNativeBorder()) {
6015 switch (sc) {
6016 case SC_ToolButton: return rule.borderRect(opt->rect);
6017 case SC_ToolButtonMenu: {
6018 QRenderRule subRule = renderRule(w, opt, PseudoElement_ToolButtonMenu);
6019 return positionRect(w, rule, subRule, PseudoElement_ToolButtonMenu, opt->rect, opt->direction);
6020 }
6021 default:
6022 break;
6023 }
6024 }
6025
6026 QStyleOptionToolButton tool(*tb);
6027 tool.rect = rule.borderRect(opt->rect);
6028 return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &tool, sc, w)
6029 : QWindowsStyle::subControlRect(cc, &tool, sc, w);
6030 }
6031#endif // QT_CONFIG(toolbutton)
6032 break;
6033
6034#if QT_CONFIG(scrollbar)
6035 case CC_ScrollBar:
6036 if (const QStyleOptionSlider *sb = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6037 QStyleOptionSlider styleOptionSlider(*sb);
6038 styleOptionSlider.rect = rule.borderRect(opt->rect);
6039 if (rule.hasDrawable() || rule.hasBox()) {
6040 QRect grooveRect;
6041 if (!rule.hasBox()) {
6042 grooveRect = rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, sb, SC_ScrollBarGroove, w)
6043 : QWindowsStyle::subControlRect(cc, sb, SC_ScrollBarGroove, w);
6044 } else {
6045 grooveRect = rule.contentsRect(opt->rect);
6046 }
6047
6048 PseudoElement pe = PseudoElement_None;
6049
6050 switch (sc) {
6051 case SC_ScrollBarGroove:
6052 return grooveRect;
6053 case SC_ScrollBarAddPage:
6054 case SC_ScrollBarSubPage:
6055 case SC_ScrollBarSlider: {
6056 QRect contentRect = grooveRect;
6057 if (hasStyleRule(w, PseudoElement_ScrollBarSlider)) {
6058 QRenderRule sliderRule = renderRule(w, opt, PseudoElement_ScrollBarSlider);
6059 Origin origin = sliderRule.hasPosition() ? sliderRule.position()->origin : defaultOrigin(PseudoElement_ScrollBarSlider);
6060 contentRect = rule.originRect(opt->rect, origin);
6061 }
6062 int maxlen = (styleOptionSlider.orientation == Qt::Horizontal) ? contentRect.width() : contentRect.height();
6063 int sliderlen;
6064 if (sb->maximum != sb->minimum) {
6065 uint range = sb->maximum - sb->minimum;
6066 sliderlen = (qint64(sb->pageStep) * maxlen) / (range + sb->pageStep);
6067
6068 int slidermin = pixelMetric(PM_ScrollBarSliderMin, sb, w);
6069 if (sliderlen < slidermin || range > INT_MAX / 2)
6070 sliderlen = slidermin;
6071 if (sliderlen > maxlen)
6072 sliderlen = maxlen;
6073 } else {
6074 sliderlen = maxlen;
6075 }
6076 int sliderstart = (styleOptionSlider.orientation == Qt::Horizontal ? contentRect.left() : contentRect.top())
6077 + sliderPositionFromValue(sb->minimum, sb->maximum, sb->sliderPosition,
6078 maxlen - sliderlen, sb->upsideDown);
6079
6080 QRect sr = (sb->orientation == Qt::Horizontal)
6081 ? QRect(sliderstart, contentRect.top(), sliderlen, contentRect.height())
6082 : QRect(contentRect.left(), sliderstart, contentRect.width(), sliderlen);
6083 if (sc == SC_ScrollBarSubPage)
6084 sr = QRect(contentRect.topLeft(), sb->orientation == Qt::Horizontal ? sr.bottomLeft() : sr.topRight());
6085 else if (sc == SC_ScrollBarAddPage)
6086 sr = QRect(sb->orientation == Qt::Horizontal ? sr.topRight() : sr.bottomLeft(), contentRect.bottomRight());
6087 return visualRect(styleOptionSlider.direction, grooveRect, sr);
6088 }
6089 case SC_ScrollBarAddLine: pe = PseudoElement_ScrollBarAddLine; break;
6090 case SC_ScrollBarSubLine: pe = PseudoElement_ScrollBarSubLine; break;
6091 case SC_ScrollBarFirst: pe = PseudoElement_ScrollBarFirst; break;
6092 case SC_ScrollBarLast: pe = PseudoElement_ScrollBarLast; break;
6093 default: break;
6094 }
6095 if (hasStyleRule(w,pe)) {
6096 QRenderRule subRule = renderRule(w, opt, pe);
6097 if (subRule.hasPosition() || subRule.hasGeometry() || subRule.hasBox()) {
6098 const QStyleSheetPositionData *pos = subRule.position();
6099 QRect originRect = grooveRect;
6100 if (rule.hasBox()) {
6101 Origin origin = (pos && pos->origin != Origin_Unknown) ? pos->origin : defaultOrigin(pe);
6102 originRect = rule.originRect(opt->rect, origin);
6103 }
6104 return positionRect(w, subRule, pe, originRect, styleOptionSlider.direction);
6105 }
6106 }
6107 }
6108 return rule.baseStyleCanDraw() ? baseStyle()->subControlRect(cc, &styleOptionSlider, sc, w)
6109 : QWindowsStyle::subControlRect(cc, &styleOptionSlider, sc, w);
6110 }
6111 break;
6112#endif // QT_CONFIG(scrollbar)
6113
6114#if QT_CONFIG(slider)
6115 case CC_Slider:
6116 if (const QStyleOptionSlider *slider = qstyleoption_cast<const QStyleOptionSlider *>(opt)) {
6117 QRenderRule subRule = renderRule(w, opt, PseudoElement_SliderGroove);
6118 if (!subRule.hasDrawable())
6119 break;
6120 subRule.img = nullptr;
6121 QRect gr = positionRect(w, rule, subRule, PseudoElement_SliderGroove, opt->rect, opt->direction);
6122 switch (sc) {
6123 case SC_SliderGroove:
6124 return gr;
6125 case SC_SliderHandle: {
6126 bool horizontal = slider->orientation & Qt::Horizontal;
6127 QRect cr = subRule.contentsRect(gr);
6128 QRenderRule subRule2 = renderRule(w, opt, PseudoElement_SliderHandle);
6129 int len = horizontal ? subRule2.size().width() : subRule2.size().height();
6130 subRule2.img = nullptr;
6131 subRule2.geo = nullptr;
6132 cr = positionRect(w, subRule2, PseudoElement_SliderHandle, cr, opt->direction);
6133 int thickness = horizontal ? cr.height() : cr.width();
6134 int sliderPos = sliderPositionFromValue(slider->minimum, slider->maximum, slider->sliderPosition,
6135 (horizontal ? cr.width() : cr.height()) - len, slider->upsideDown);
6136 cr = horizontal ? QRect(cr.x() + sliderPos, cr.y(), len, thickness)
6137 : QRect(cr.x(), cr.y() + sliderPos, thickness, len);
6138 return subRule2.borderRect(cr);
6139 break; }
6140 case SC_SliderTickmarks:
6141 // TODO...
6142 default:
6143 break;
6144 }
6145 }
6146 break;
6147#endif // QT_CONFIG(slider)
6148
6149 case CC_MdiControls:
6150 if (hasStyleRule(w, PseudoElement_MdiCloseButton)
6151 || hasStyleRule(w, PseudoElement_MdiNormalButton)
6152 || hasStyleRule(w, PseudoElement_MdiMinButton)) {
6153 QList<QVariant> layout = rule.styleHint("button-layout"_L1).toList();
6154 if (layout.isEmpty())
6155 layout = subControlLayout("mNX");
6156
6157 int x = 0, width = 0;
6158 QRenderRule subRule;
6159 for (const QVariant &val : std::as_const(layout)) {
6160 int layoutButton = val.toInt();
6161 if (layoutButton < PseudoElement_MdiCloseButton
6162 || layoutButton > PseudoElement_MdiNormalButton)
6163 continue;
6164 QStyle::SubControl control = knownPseudoElements[layoutButton].subControl;
6165 if (!(opt->subControls & control))
6166 continue;
6167 subRule = renderRule(w, opt, layoutButton);
6168 width = subRule.size().width();
6169 if (sc == control)
6170 break;
6171 x += width;
6172 }
6173
6174 return subRule.borderRect(QRect(x, opt->rect.top(), width, opt->rect.height()));
6175 }
6176 break;
6177
6178 case CC_TitleBar:
6179 if (const QStyleOptionTitleBar *tb = qstyleoption_cast<const QStyleOptionTitleBar *>(opt)) {
6180 QRenderRule subRule = renderRule(w, opt, PseudoElement_TitleBar);
6181 if (!subRule.hasDrawable() && !subRule.hasBox() && !subRule.hasBorder())
6182 break;
6183 QHash<QStyle::SubControl, QRect> layoutRects = titleBarLayout(w, tb);
6184 return layoutRects.value(sc);
6185 }
6186 break;
6187
6188 default:
6189 break;
6190 }
6191
6192 return baseStyle()->subControlRect(cc, opt, sc, w);
6193}
6194
6195QRect QStyleSheetStyle::subElementRect(SubElement se, const QStyleOption *opt, const QWidget *w) const
6196{
6197 RECURSION_GUARD(return baseStyle()->subElementRect(se, opt, w))
6198
6199 QRenderRule rule = renderRule(w, opt);
6200#if QT_CONFIG(tabbar)
6201 int pe = PseudoElement_None;
6202#endif
6203
6204 switch (se) {
6205 case SE_PushButtonContents:
6206 case SE_PushButtonBevel:
6207 case SE_PushButtonFocusRect:
6208 if (const QStyleOptionButton *btn = qstyleoption_cast<const QStyleOptionButton *>(opt)) {
6209 if (btn->features & QStyleOptionButton::HasMenu
6210 && hasStyleRule(w, PseudoElement_PushButtonMenuIndicator)) {
6211 QStyleOptionButton btnOpt(*btn);
6212 btnOpt.features &= ~QStyleOptionButton::HasMenu;
6213 return rule.baseStyleCanDraw() ? baseStyle()->subElementRect(se, &btnOpt, w)
6214 : QWindowsStyle::subElementRect(se, &btnOpt, w);
6215 }
6216 if (rule.hasBox() || !rule.hasNativeBorder()) {
6217 return visualRect(opt->direction, opt->rect, se == SE_PushButtonBevel
6218 ? rule.borderRect(opt->rect)
6219 : rule.contentsRect(opt->rect));
6220 }
6221 return rule.baseStyleCanDraw() ? baseStyle()->subElementRect(se, btn, w)
6222 : QWindowsStyle::subElementRect(se, btn, w);
6223 }
6224 break;
6225
6226 case SE_LineEditContents:
6227 case SE_FrameContents:
6228 case SE_ShapedFrameContents:
6229 if (rule.hasBox() || !rule.hasNativeBorder()) {
6230 return visualRect(opt->direction, opt->rect, rule.contentsRect(opt->rect));
6231 }
6232 break;
6233
6234 case SE_CheckBoxIndicator:
6235 case SE_RadioButtonIndicator:
6236 if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
6237 PseudoElement pe = se == SE_CheckBoxIndicator ? PseudoElement_Indicator : PseudoElement_ExclusiveIndicator;
6238 QRenderRule subRule = renderRule(w, opt, pe);
6239 return positionRect(w, rule, subRule, pe, opt->rect, opt->direction);
6240 }
6241 break;
6242
6243 case SE_CheckBoxContents:
6244 case SE_RadioButtonContents:
6245 if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
6246 bool isRadio = se == SE_RadioButtonContents;
6247 QRect ir = subElementRect(isRadio ? SE_RadioButtonIndicator : SE_CheckBoxIndicator,
6248 opt, w);
6249 ir = visualRect(opt->direction, opt->rect, ir);
6250 int spacing = pixelMetric(isRadio ? PM_RadioButtonLabelSpacing : PM_CheckBoxLabelSpacing, nullptr, w);
6251 QRect cr = rule.contentsRect(opt->rect);
6252 ir.setRect(ir.left() + ir.width() + spacing, cr.y(),
6253 cr.width() - ir.width() - spacing, cr.height());
6254 return visualRect(opt->direction, opt->rect, ir);
6255 }
6256 break;
6257
6258 case SE_ToolBoxTabContents:
6259 if (w && hasStyleRule(w->parentWidget(), PseudoElement_ToolBoxTab)) {
6260 QRenderRule subRule = renderRule(w->parentWidget(), opt, PseudoElement_ToolBoxTab);
6261 return visualRect(opt->direction, opt->rect, subRule.contentsRect(opt->rect));
6262 }
6263 break;
6264
6265 case SE_RadioButtonFocusRect:
6266 case SE_RadioButtonClickRect: // focusrect | indicator
6267 if (rule.hasBox() || rule.hasBorder() || hasStyleRule(w, PseudoElement_Indicator)) {
6268 return opt->rect;
6269 }
6270 break;
6271
6272 case SE_CheckBoxFocusRect:
6273 case SE_CheckBoxClickRect: // relies on indicator and contents
6274 return ParentStyle::subElementRect(se, opt, w);
6275
6276#if QT_CONFIG(itemviews)
6277 case SE_ItemViewItemCheckIndicator:
6278 if (!qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
6279 return subElementRect(SE_CheckBoxIndicator, opt, w);
6280 }
6281 Q_FALLTHROUGH();
6282 case SE_ItemViewItemText:
6283 case SE_ItemViewItemDecoration:
6284 case SE_ItemViewItemFocusRect:
6285 if (const QStyleOptionViewItem *vopt = qstyleoption_cast<const QStyleOptionViewItem *>(opt)) {
6286 QRenderRule subRule = renderRule(w, opt, PseudoElement_ViewItem);
6287 PseudoElement pe = PseudoElement_None;
6288 if (se == SE_ItemViewItemText || se == SE_ItemViewItemFocusRect)
6289 pe = PseudoElement_ViewItemText;
6290 else if (se == SE_ItemViewItemDecoration && vopt->features & QStyleOptionViewItem::HasDecoration)
6291 pe = PseudoElement_ViewItemIcon;
6292 else if (se == SE_ItemViewItemCheckIndicator && vopt->features & QStyleOptionViewItem::HasCheckIndicator)
6293 pe = PseudoElement_ViewItemIndicator;
6294 else
6295 break;
6296 if (subRule.hasGeometry() || subRule.hasBox() || !subRule.hasNativeBorder() || hasStyleRule(w, pe)) {
6297 QRenderRule subRule2 = renderRule(w, opt, pe);
6298 QStyleOptionViewItem optCopy(*vopt);
6299 optCopy.rect = subRule.contentsRect(vopt->rect);
6300 QRect rect = ParentStyle::subElementRect(se, &optCopy, w);
6301 return positionRect(w, subRule2, pe, rect, opt->direction);
6302 }
6303 }
6304 break;
6305#endif // QT_CONFIG(itemviews)
6306
6307 case SE_HeaderArrow: {
6308 QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewUpArrow);
6309 if (subRule.hasPosition() || subRule.hasGeometry())
6310 return positionRect(w, rule, subRule, PseudoElement_HeaderViewUpArrow, opt->rect, opt->direction);
6311 }
6312 break;
6313
6314 case SE_HeaderLabel: {
6315 QRenderRule subRule = renderRule(w, opt, PseudoElement_HeaderViewSection);
6316 if (subRule.hasBox() || !subRule.hasNativeBorder()) {
6317 auto r = subRule.contentsRect(opt->rect);
6318 return r;
6319 }
6320 }
6321 break;
6322
6323 case SE_ProgressBarGroove:
6324 case SE_ProgressBarContents:
6325 case SE_ProgressBarLabel:
6326 if (const QStyleOptionProgressBar *pb = qstyleoption_cast<const QStyleOptionProgressBar *>(opt)) {
6327 if (rule.hasBox() || !rule.hasNativeBorder() || rule.hasPosition() || hasStyleRule(w, PseudoElement_ProgressBarChunk)) {
6328 if (se == SE_ProgressBarGroove)
6329 return rule.borderRect(pb->rect);
6330 else if (se == SE_ProgressBarContents)
6331 return rule.contentsRect(pb->rect);
6332
6333 QSize sz = pb->fontMetrics.size(0, pb->text);
6334 return QStyle::alignedRect(Qt::LeftToRight, rule.hasPosition() ? rule.position()->textAlignment : pb->textAlignment,
6335 sz, pb->rect);
6336 }
6337 }
6338 break;
6339
6340#if QT_CONFIG(tabbar)
6341 case SE_TabWidgetLeftCorner:
6342 pe = PseudoElement_TabWidgetLeftCorner;
6343 Q_FALLTHROUGH();
6344 case SE_TabWidgetRightCorner:
6345 if (pe == PseudoElement_None)
6346 pe = PseudoElement_TabWidgetRightCorner;
6347 Q_FALLTHROUGH();
6348 case SE_TabWidgetTabBar:
6349 if (pe == PseudoElement_None)
6350 pe = PseudoElement_TabWidgetTabBar;
6351 Q_FALLTHROUGH();
6352 case SE_TabWidgetTabPane:
6353 case SE_TabWidgetTabContents:
6354 if (pe == PseudoElement_None)
6355 pe = PseudoElement_TabWidgetPane;
6356
6357 if (hasStyleRule(w, pe)) {
6358 QRect r = QWindowsStyle::subElementRect(pe == PseudoElement_TabWidgetPane ? SE_TabWidgetTabPane : se, opt, w);
6359 QRenderRule subRule = renderRule(w, opt, pe);
6360 r = positionRect(w, subRule, pe, r, opt->direction);
6361 if (pe == PseudoElement_TabWidgetTabBar) {
6362 Q_ASSERT(opt);
6363 r = opt->rect.intersected(r);
6364 }
6365 if (se == SE_TabWidgetTabContents)
6366 r = subRule.contentsRect(r);
6367 return r;
6368 }
6369 break;
6370
6371 case SE_TabBarScrollLeftButton:
6372 case SE_TabBarScrollRightButton:
6373 if (hasStyleRule(w, PseudoElement_TabBarScroller)) {
6374 QStyleSheetProxySaver proxySaver(this);
6375 return baseStyle()->subElementRect(se, opt, w);
6376 }
6377 break;
6378
6379 case SE_TabBarTearIndicator: {
6380 QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTear);
6381 if (subRule.hasContentsSize()) {
6382 QRect r;
6383 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
6384 switch (tab->shape) {
6385 case QTabBar::RoundedNorth:
6386 case QTabBar::TriangularNorth:
6387 case QTabBar::RoundedSouth:
6388 case QTabBar::TriangularSouth:
6389 r.setRect(tab->rect.left(), tab->rect.top(), subRule.size().width(), opt->rect.height());
6390 break;
6391 case QTabBar::RoundedWest:
6392 case QTabBar::TriangularWest:
6393 case QTabBar::RoundedEast:
6394 case QTabBar::TriangularEast:
6395 r.setRect(tab->rect.left(), tab->rect.top(), opt->rect.width(), subRule.size().height());
6396 break;
6397 default:
6398 break;
6399 }
6400 r = visualRect(opt->direction, opt->rect, r);
6401 }
6402 return r;
6403 }
6404 break;
6405 }
6406 case SE_TabBarTabText:
6407 case SE_TabBarTabLeftButton:
6408 case SE_TabBarTabRightButton: {
6409 QRenderRule subRule = renderRule(w, opt, PseudoElement_TabBarTab);
6410 if (subRule.hasBox() || !subRule.hasNativeBorder() || subRule.hasFont) {
6411 if (se == SE_TabBarTabText) {
6412 if (const QStyleOptionTab *tab = qstyleoption_cast<const QStyleOptionTab *>(opt)) {
6413 const QTabBar *bar = qobject_cast<const QTabBar *>(w);
6414 const QRect optRect = bar && tab->tabIndex != -1 ? bar->tabRect(tab->tabIndex) : opt->rect;
6415 const QRect r = positionRect(w, subRule, PseudoElement_TabBarTab, optRect, opt->direction);
6416 QStyleOptionTab tabCopy(*tab);
6417 if (subRule.hasFont) {
6418 const QFont ruleFont = w ? subRule.font.resolve(w->font()) : subRule.font;
6419 tabCopy.fontMetrics = QFontMetrics(ruleFont);
6420 }
6421 tabCopy.rect = subRule.contentsRect(r);
6422 return ParentStyle::subElementRect(se, &tabCopy, w);
6423 }
6424 }
6425 return ParentStyle::subElementRect(se, opt, w);
6426 }
6427 break;
6428 }
6429#endif // QT_CONFIG(tabbar)
6430
6431 case SE_DockWidgetCloseButton:
6432 case SE_DockWidgetFloatButton: {
6433 PseudoElement pe = (se == SE_DockWidgetCloseButton) ? PseudoElement_DockWidgetCloseButton : PseudoElement_DockWidgetFloatButton;
6434 QRenderRule subRule2 = renderRule(w, opt, pe);
6435 if (!subRule2.hasPosition())
6436 break;
6437 QRenderRule subRule = renderRule(w, opt, PseudoElement_DockWidgetTitle);
6438 return positionRect(w, subRule, subRule2, pe, opt->rect, opt->direction);
6439 }
6440
6441#if QT_CONFIG(toolbar)
6442 case SE_ToolBarHandle:
6443 if (hasStyleRule(w, PseudoElement_ToolBarHandle))
6444 return ParentStyle::subElementRect(se, opt, w);
6445 break;
6446#endif // QT_CONFIG(toolbar)
6447
6448 // On mac we make pixel adjustments to layouts which are not
6449 // desirable when you have custom style sheets on them
6450 case SE_CheckBoxLayoutItem:
6451 case SE_ComboBoxLayoutItem:
6452 case SE_DateTimeEditLayoutItem:
6453 case SE_LabelLayoutItem:
6454 case SE_ProgressBarLayoutItem:
6455 case SE_PushButtonLayoutItem:
6456 case SE_RadioButtonLayoutItem:
6457 case SE_SliderLayoutItem:
6458 case SE_SpinBoxLayoutItem:
6459 case SE_ToolButtonLayoutItem:
6460 case SE_FrameLayoutItem:
6461 case SE_GroupBoxLayoutItem:
6462 case SE_TabWidgetLayoutItem:
6463 if (!rule.hasNativeBorder())
6464 return opt->rect;
6465 break;
6466
6467 default:
6468 break;
6469 }
6470
6471 return baseStyle()->subElementRect(se, opt, w);
6472}
6473
6474bool QStyleSheetStyle::event(QEvent *e)
6475{
6476 return (baseStyle()->event(e) && e->isAccepted()) || ParentStyle::event(e);
6477}
6478
6479void QStyleSheetStyle::updateStyleSheetFont(QWidget* w) const
6480{
6481 // Qt's fontDialog relies on the font of the sample edit for its selection,
6482 // we should never override it.
6483 if (w->objectName() == "qt_fontDialog_sampleEdit"_L1)
6484 return;
6485
6486 const QWidget *container = containerWidget(w);
6487 QRenderRule rule = renderRule(container, PseudoElement_None,
6488 PseudoClass_Active | PseudoClass_Enabled | extendedPseudoClass(container));
6489
6490 const bool useStyleSheetPropagationInWidgetStyles =
6491 QCoreApplication::testAttribute(Qt::AA_UseStyleSheetPropagationInWidgetStyles);
6492
6493 if (useStyleSheetPropagationInWidgetStyles) {
6494 unsetStyleSheetFont(w);
6495
6496 if (rule.font.resolveMask()) {
6497 QFont wf = w->d_func()->localFont();
6498 styleSheetCaches->customFontWidgets.insert(w, {wf, rule.font.resolveMask()});
6499
6500 QFont font = rule.font.resolve(wf);
6501 font.setResolveMask(wf.resolveMask() | rule.font.resolveMask());
6502 w->setFont(font);
6503 }
6504 } else {
6505 QFont wf = w->d_func()->localFont();
6506 QFont font = rule.font.resolve(wf);
6507 font.setResolveMask(wf.resolveMask() | rule.font.resolveMask());
6508
6509 if ((!w->isWindow() || w->testAttribute(Qt::WA_WindowPropagation))
6510 && isNaturalChild(w) && w->parentWidget()) {
6511 const auto parentFont = w->parentWidget()->font();
6512 font = rule.hasFont ? font.resolve(parentFont) : parentFont;
6513 }
6514
6515 if (wf.resolveMask() == font.resolveMask() && wf == font)
6516 return;
6517
6518 w->data->fnt = font;
6519 w->d_func()->directFontResolveMask = font.resolveMask();
6520
6521 QEvent e(QEvent::FontChange);
6522 QCoreApplication::sendEvent(w, &e);
6523 }
6524}
6525
6526void QStyleSheetStyle::saveWidgetFont(QWidget* w, const QFont& font) const
6527{
6528 w->setProperty("_q_styleSheetWidgetFont", font);
6529}
6530
6531void QStyleSheetStyle::clearWidgetFont(QWidget* w) const
6532{
6533 w->setProperty("_q_styleSheetWidgetFont", QVariant());
6534}
6535
6536// Polish palette that should be used for a particular widget, with particular states
6537// (eg. :focus, :hover, ...)
6538// this is called by widgets that paint themself in their paint event
6539// Returns \c true if there is a new palette in pal.
6540bool QStyleSheetStyle::styleSheetPalette(const QWidget* w, const QStyleOption* opt, QPalette* pal)
6541{
6542 if (!w || !opt || !pal)
6543 return false;
6544
6545 RECURSION_GUARD(return false)
6546
6547 w = containerWidget(w);
6548
6549 QRenderRule rule = renderRule(w, PseudoElement_None, pseudoClass(opt->state) | extendedPseudoClass(w));
6550 if (!rule.hasPalette())
6551 return false;
6552
6553 rule.configurePalette(pal, QPalette::NoRole, QPalette::NoRole);
6554 return true;
6555}
6556
6557Qt::Alignment QStyleSheetStyle::resolveAlignment(Qt::LayoutDirection layDir, Qt::Alignment src)
6558{
6559 if (layDir == Qt::LeftToRight || src & Qt::AlignAbsolute)
6560 return src;
6561
6562 if (src & Qt::AlignLeft) {
6563 src &= ~Qt::AlignLeft;
6564 src |= Qt::AlignRight;
6565 } else if (src & Qt::AlignRight) {
6566 src &= ~Qt::AlignRight;
6567 src |= Qt::AlignLeft;
6568 }
6569 src |= Qt::AlignAbsolute;
6570 return src;
6571}
6572
6573// Returns whether the given QWidget has a "natural" parent, meaning that
6574// the parent contains this child as part of its normal operation.
6575// An example is the QTabBar inside a QTabWidget.
6576// This does not mean that any QTabBar which is a child of QTabWidget will
6577// match, only the one that was created by the QTabWidget initialization
6578// (and hence has the correct object name).
6579bool QStyleSheetStyle::isNaturalChild(const QObject *obj)
6580{
6581 if (obj->objectName().startsWith("qt_"_L1))
6582 return true;
6583
6584 return false;
6585}
6586
6587QPixmap QStyleSheetStyle::loadPixmap(const QString &fileName, const QObject *context)
6588{
6589 if (fileName.isEmpty())
6590 return {};
6591
6592 qreal ratio = -1.0;
6593 if (const QWidget *widget = qobject_cast<const QWidget *>(context)) {
6594 if (QScreen *screen = QApplication::screenAt(widget->mapToGlobal(QPoint(0, 0))))
6595 ratio = screen->devicePixelRatio();
6596 }
6597
6598 if (ratio < 0) {
6599 if (const QApplication *app = qApp)
6600 ratio = app->devicePixelRatio();
6601 else
6602 ratio = 1.0;
6603 }
6604
6605 qreal sourceDevicePixelRatio = 1.0;
6606 QString resolvedFileName = qt_findAtNxFile(fileName, ratio, &sourceDevicePixelRatio);
6607 QPixmap pixmap(resolvedFileName);
6608 pixmap.setDevicePixelRatio(sourceDevicePixelRatio);
6609 return pixmap;
6610}
6611
6612QT_END_NAMESPACE
6613
6614#include "moc_qstylesheetstyle_p.cpp"
6615
6616#endif // QT_CONFIG(style_stylesheet)