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