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