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