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