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
qqstylekitstyle.cpp
Go to the documentation of this file.
1// Copyright (C) 2025 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
4#include "qqstylekit_p.h"
11
12#include <QtQuickTemplates2/private/qquickdeferredexecute_p_p.h>
13#include <QtQml/private/qqmllist_p.h>
14
15#include <QtGui/QGuiApplication>
16#include <QtGui/QStyleHints>
17
19
20/*!
21 \qmltype Style
22 \inqmlmodule Qt.labs.StyleKit
23 \inherits AbstractStyle
24 \brief The root type for a style definition.
25
26 \l Style is the root type in StyleKit for defining a complete visual style for
27 \l [QtQuickControls] {Qt Quick Controls}. A style lets you customize
28 the appearance of \l {StylableControls}{every control type}
29 — \l {ControlStateStyle::background}{backgrounds}, \l {ControlStateStyle::indicator}{indicators},
30 \l {ControlStateStyle::handle}{handles}, \l {ControlStateStyle::}{text},
31 \l {ControlStateStyle::}{padding}, and more
32 — as well as how controls respond to states
33 such as \l {ControlStyle::}{hovered},
34 \l {ControlStyle::}{pressed}, and
35 \l {ControlStyle::}{disabled}, including animated
36 \l {ControlStyle::transition}{transitions} between them.
37
38 Styles support \l light and \l dark color schemes through \l {Theme}
39 {themes}, and you can add any number of \l {CustomTheme}{custom themes}
40 as well. \l {StyleVariation}{Style variations} allow you to define
41 alternative styling that can be applied to specific control instances
42 or entire control types. You can also define \l {CustomControl}
43 {custom controls} to extend the style beyond the built-in control set.
44
45 The following example shows a minimal style that defines some structural
46 properties shared by all themes, with separate light and dark themes for colors:
47
48 \snippet PlainStyle.qml 1
49
50 For a more complete example, see the \l{StyleKit Quick Controls Example}.
51
52 \labs
53
54 \sa Theme, CustomTheme, StyleVariation, ControlStyle, DelegateStyle,
55 CustomControl, {StyleKit Property Resolution}
56*/
57
58/*!
59 \qmlproperty list<string> Style::customThemeNames
60 \readonly
61
62 The names of all the \l {CustomTheme}{custom themes} defined in the style. This does not
63 include the \l{availableThemeNames}{built-in themes.}
64
65 \sa availableThemeNames, themeName, CustomTheme
66*/
67
68/*!
69 \qmlproperty Component Style::dark
70
71 The dark theme component. It's instantiated and applied when the system is in
72 dark mode and \l themeName is \c "System", or when \l themeName is
73 explicitly set to \c "Dark".
74
75 \snippet StyleSnippets.qml dark
76
77 \sa light, themeName
78*/
79
80/*!
81 \qmlproperty Style Style::fallbackStyle
82
83 The fallback style used to resolve properties that are not explicitly
84 set in this style. When a property is not found in the style or its
85 active theme, StyleKit looks it up in the fallback style.
86
87 By default, the fallback style is set to an internal style that provides
88 a basic appearance similar to the \l {Basic Style}{Basic} style.
89
90 You can set this to a custom Style, or to \c null to disable
91 fallback resolution entirely. Note that setting it to \c null
92 means starting from a completely clean slate, which requires
93 you to set many more properties than otherwise needed. A
94 reference implementation of a fallback style can be found
95 \l {qtlabsstylekit-fallbackstyle.html}{here.}
96*/
97
98/*!
99 \qmlproperty Component Style::light
100
101 The light theme component. It's instantiated and applied when the system is in
102 light mode and \l themeName is \c "System", or when \l themeName is
103 explicitly set to \c "Light".
104
105 \snippet StyleSnippets.qml light
106
107 \sa dark, themeName
108*/
109
110/*!
111 \qmlproperty palette Style::palette
112 \readonly
113
114 The palette of the control being styled.
115
116 Use this palette to bind colors in the style to the
117 \l {StyleReader::palette}{palette} of the control being styled.
118 If the application assigns a different palette to a control, the
119 style will adapt, and the control will repaint.
120
121 \snippet StyleSnippets.qml palette
122
123 \sa StyleReader::palette
124*/
125
126/*!
127 \qmlproperty Theme Style::theme
128 \readonly
129
130 The currently active theme instance.
131 It's instantiated from either the \l {light}{light theme component}, the
132 \l {dark}{dark theme component}, or one of the \l {CustomTheme}{custom themes},
133 depending on \l themeName.
134
135 When resolving a style property, StyleKit first looks for it in this
136 theme (\l {StyleVariation}{StyleVariations} aside). If the property is not found, it
137 falls back to search for it in the \l Style.
138
139 \sa themeName, light, dark
140*/
141
142/*!
143 \qmlproperty string Style::themeName
144
145 The name of the active theme. The default value is \c "System",
146 which automatically choose between \l light or \l dark depending on the
147 color scheme reported by \l QStyleHints::colorScheme.
148
149 You can set this property to change the theme of \e this style.
150 For the theme to take effect in the application, the style it belongs
151 to must also be the \l{StyleKit::style}{current style}.
152
153 \snippet StyleSnippets.qml themeName
154
155 Supported values:
156 \list
157 \li \c "System" \mdash follows \l QStyleHints::colorScheme (default)
158 \li \c "Light" \mdash forces the \l light theme
159 \li \c "Dark" \mdash forces the \l dark theme
160 \li \l {customThemeNames}{Any custom theme name}
161 \endlist
162
163 Themes are local to the \l Style where they are defined, and can only be set
164 as the theme for that style. Changing the theme does not propagate to
165 the \l {Style::fallbackStyle}{fallback style}. If the fallback style has its
166 own themes and you want to change its theme as well, set \l themeName on
167 each style in the chain explicitly, for example:
168
169 \qml
170 for (let style = StyleKit.style; style; style = style.fallbackStyle)
171 style.themeName = "Dark"
172 \endqml
173
174 \sa availableThemeNames, theme
175*/
176
177/*!
178 \qmlproperty list<string> Style::availableThemeNames
179 \readonly
180
181 The names of all available themes, including \c "System", \c "Light",
182 \c "Dark", and any \l {customThemeNames}{custom themes.}
183
184 \sa themeName, customThemeNames
185*/
186
187static const QString kSystem = "System"_L1;
188static const QString kLight = "Light"_L1;
189static const QString kDark = "Dark"_L1;
190
191QQStyleKitStyle::QQStyleKitStyle(QObject *parent)
192 : QQStyleKitStyleAndThemeBase(parent)
193 , m_paletteProxy(new QQuickPalette(this))
194 , m_themeName(kSystem)
195{
196 s_allStyles.append(this);
197}
198
199QQStyleKitStyle::~QQStyleKitStyle()
200{
201 s_allStyles.removeOne(this);
202 if (m_theme)
203 m_theme->deleteLater();
204}
205
206void QQStyleKitStyle::forEachStyle(const std::function<void (QQStyleKitStyle *style)> &f)
207{
208 const QList<QQStyleKitStyle *> allStyleTmp = s_allStyles;
209 for (QQStyleKitStyle *style : allStyleTmp) {
210 if (!s_allStyles.contains(style)) {
211 /* The style was destroyed by the app during the loop. Note that a
212 * new style added to s_allStyles could theoretically replace the same
213 * address, but that would still be a valid Style, so it's fine. */
214 continue;
215 }
216 f(style);
217 }
218}
219
220QQuickPalette *QQStyleKitStyle::palette() const
221{
222 return m_paletteProxy;
223}
224
225QQmlComponent *QQStyleKitStyle::light() const
226{
227 return m_light;
228}
229
230QQStyleKitStyle *QQStyleKitStyle::fallbackStyle() const
231{
232 if (!m_fallbackStyle) {
233 auto *self = const_cast<QQStyleKitStyle *>(this);
234 self->executeFallbackStyle();
235 }
236 return m_fallbackStyle;
237}
238
239void QQStyleKitStyle::setFallbackStyle(QQStyleKitStyle *fallbackStyle)
240{
241 if (m_fallbackStyle == fallbackStyle)
242 return;
243
244 if (fallbackStyle && fallbackStyle->dependsOn(this)) {
245 qmlWarning(this) << "Cannot set fallbackStyle to style with objectName '"
246 << fallbackStyle->objectName()
247 << "', since that would create a loop in the fallback chain!";
248 return;
249 }
250
251 m_fallbackStyle = fallbackStyle;
252
253 if (palettes())
254 palettes()->setFallbackPalette(m_fallbackStyle ? m_fallbackStyle->palettes() : nullptr);
255
256 if (fonts())
257 fonts()->setFallbackFont(m_fallbackStyle ? m_fallbackStyle->fonts() : nullptr);
258
259 reapplyStylesDependingOnThis();
260 emit fallbackStyleChanged();
261}
262
263void QQStyleKitStyle::setLight(QQmlComponent *lightTheme)
264{
265 if (m_light == lightTheme)
266 return;
267
268 m_light = lightTheme;
269
270 emit lightChanged();
271}
272
273QQmlComponent *QQStyleKitStyle::dark() const
274{
275 return m_dark;
276}
277
278void QQStyleKitStyle::setDark(QQmlComponent *darkTheme)
279{
280 if (m_dark == darkTheme)
281 return;
282
283 m_dark = darkTheme;
284
285 emit darkChanged();
286}
287
288QQStyleKitTheme *QQStyleKitStyle::theme() const
289{
290 return m_theme;
291}
292
293QList<QQStyleKitCustomTheme *> QQStyleKitStyle::customThemes() const
294{
295 QList<QQStyleKitCustomTheme *> list;
296 for (auto *obj : children()) {
297 if (auto *customTheme = qobject_cast<QQStyleKitCustomTheme *>(obj))
298 list.append(customTheme);
299 }
300 return list;
301}
302
303void QQStyleKitStyle::parseThemes()
304{
305 m_availableThemeNames = QStringList({kSystem});
306
307 if (m_light)
308 m_availableThemeNames << kLight;
309 if (m_dark)
310 m_availableThemeNames << kDark;
311
312 for (auto *customTheme : customThemes()) {
313 const QString name = customTheme->name();
314 if (name.isEmpty())
315 continue;
316 m_availableThemeNames << name;
317 m_customThemeNames << name;
318 }
319
320 emit availableThemeNamesChanged();
321 emit customThemeNamesChanged();
322}
323
324QString QQStyleKitStyle::themeName() const
325{
326 return m_themeName;
327}
328
329QStringList QQStyleKitStyle::availableThemeNames() const
330{
331 return m_availableThemeNames;
332}
333
334QStringList QQStyleKitStyle::customThemeNames() const
335{
336 return m_customThemeNames;
337}
338
339void QQStyleKitStyle::setThemeName(const QString &themeName)
340{
341 if (m_themeName == themeName)
342 return;
343
344 m_themeName = themeName;
345
346 if (m_completed) {
347 recreateTheme();
348 reapplyStylesDependingOnThis();
349 }
350
351 emit themeNameChanged();
352}
353
354void QQStyleKitStyle::recreateTheme()
355{
356 QString effectiveThemeName;
357 QQmlComponent *effectiveThemeComponent = nullptr;
358
359 if (QString::compare(m_themeName, kSystem, Qt::CaseInsensitive) == 0) {
360 switch (QGuiApplication::styleHints()->colorScheme()) {
361 case Qt::ColorScheme::Dark:
362 effectiveThemeName = kDark;
363 effectiveThemeComponent = m_dark;
364 break;
365 case Qt::ColorScheme::Light:
366 case Qt::ColorScheme::Unknown:
367 effectiveThemeName = kLight;
368 effectiveThemeComponent = m_light;
369 break;
370 // Intentionally skipping a default case here, so that if a new scheme is added
371 // in the future, we get a warning about an unhandled enum value, which will prompt
372 // us to consider if we need to add explicit support for it in StyleKit as well.
373 }
374 } else if (QString::compare(m_themeName, kLight, Qt::CaseInsensitive) == 0) {
375 effectiveThemeName = kLight;
376 effectiveThemeComponent = m_light;
377 } else if (QString::compare(m_themeName,kDark, Qt::CaseInsensitive) == 0) {
378 effectiveThemeName =kDark;
379 effectiveThemeComponent = m_dark;
380 } else if (!m_themeName.isEmpty()){
381 for (auto *customTheme : customThemes()) {
382 if (QString::compare(m_themeName, customTheme->name(), Qt::CaseInsensitive) == 0) {
383 effectiveThemeName = customTheme->name();
384 effectiveThemeComponent = customTheme->theme();
385 break;
386 }
387 }
388 if (effectiveThemeName.isEmpty())
389 qmlWarning(this) << "No theme found with themeName '" << m_themeName << "'";
390 else if (!effectiveThemeComponent)
391 qmlWarning(this) << "Custom theme '" << effectiveThemeName << "' has no theme component set";
392 }
393
394 if (m_theme) {
395 if (m_effectiveThemeName == effectiveThemeName)
396 return;
397
398 m_theme->deleteLater();
399 m_theme = nullptr;
400 }
401
402 m_effectiveThemeName = effectiveThemeName;
403 m_currentThemeComponent = effectiveThemeComponent;
404
405 if (effectiveThemeComponent) {
406 if (effectiveThemeComponent->status() != QQmlComponent::Ready) {
407 qmlWarning(this) << "failed to create theme '" << effectiveThemeName << "': " << effectiveThemeComponent->errorString();
408 } else {
409 /* The 'createThemeInsideStyle' JS function is a work-around since we haven't found
410 * a way to instantiate a Theme inside the context of a Style from c++. Doing so is
411 * needed in order to allow custom style properties to be added as children of a
412 * Style, and at the same time, be able to access them from within a Theme. For
413 * this to work, the Style also needs to set 'pragma ComponentBehavior: Bound'. */
414 QVariant themeAsVariant;
415 QMetaObject::invokeMethod(this, "createThemeInsideStyle", Qt::DirectConnection,
416 qReturnArg(themeAsVariant), QVariant::fromValue(effectiveThemeComponent));
417 m_theme = qvariant_cast<QQStyleKitTheme *>(themeAsVariant);
418
419 if (!m_theme || !effectiveThemeComponent->errorString().isEmpty()) {
420 qmlWarning(this) << "failed to create theme '" << effectiveThemeName << "': " << effectiveThemeComponent->errorString();
421 } else {
422 m_theme->setParent(this);
423 }
424 }
425 }
426
427 if (!m_theme) {
428 // We always require a theme, even if it's empty
429 m_theme = new QQStyleKitTheme(this);
430 m_theme->setObjectName("<empty theme>"_L1);
431 m_theme->m_completed = true;
432 } else {
433 m_theme->setParent(this);
434 }
435
436 if (m_theme->fonts())
437 m_theme->fonts()->setFallbackFont(fonts());
438 if (m_theme->palettes())
439 m_theme->palettes()->setFallbackPalette(palettes());
440
441 emit themeChanged();
442}
443
444void QQStyleKitStyle::reapplyStyle()
445{
446 if (!loaded())
447 return;
448
449 /* The effective palettes and fonts are resolved into the style's own theme, and
450 * read from there by the StyleReaders. This also happens when a StyleReader starts
451 * using the style at a later point (e.g. by setting it as an explicit style), in
452 * which case we don't resolve them again. So they always need to be up-to-date,
453 * even for a style that no StyleReader is reading from (yet). */
454 m_theme->updateThemePalettes();
455 m_theme->updateThemeFonts();
456
457 QQStyleKitVariation::resetVariationsForStyle(this);
458 QQStyleKitReader::resetReadersForStyle(this);
459}
460
461void QQStyleKitStyle::reapplyStylesDependingOnThis()
462{
463 /* A change to style also affects all top-level style that has it in its fallback
464 * chain. Therefore, go through all styles, find the ones that depend on this one,
465 * and reset all StyleReaders that read from them. */
466 forEachStyle([this](QQStyleKitStyle *style) {
467 if (style->dependsOn(this))
468 style->reapplyStyle();
469 });
470}
471
472QQStyleKitStyle* QQStyleKitStyle::current()
473{
474 return QQStyleKit::qmlAttachedProperties()->style();
475}
476
477QPalette QQStyleKitStyle::paletteForControlType(QQStyleKitExtendableControlType type) const
478{
479 return m_theme->paletteForControlType(type);
480}
481
482QFont QQStyleKitStyle::fontForControlType(QQStyleKitExtendableControlType type) const
483{
484 return m_theme->fontForControlType(type);
485}
486
487bool QQStyleKitStyle::loaded() const
488{
489 /* Returns false until the style has completed loading. Callers can use
490 * this to skip property reads and change notifications while loading,
491 * since a full update follows once loading is done anyway. */
492 return m_completed && m_theme && m_theme->m_completed;
493}
494
495bool QQStyleKitStyle::dependsOn(const QQStyleKitStyle *style) const
496{
497 /* Returns \c true if \a style is this style or one of its (nested)
498 * fallback styles; otherwise returns \c false.
499 * Note: read m_fallbackStyle directly rather than going through fallbackStyle(),
500 * since the latter will instantiate a deferred fallback style as a side effect.
501 * The chain cannot contain a loop, since setFallbackStyle() refuses to create one. */
502 for (const QQStyleKitStyle *fallback = this; fallback; fallback = fallback->m_fallbackStyle.data()) {
503 if (style == fallback)
504 return true;
505 }
506 return false;
507}
508
509void QQStyleKitStyle::executeFallbackStyle(bool complete)
510{
511 if (m_fallbackStyle || m_fallbackStyle.wasExecuted())
512 return;
513
514 const QString name = "fallbackStyle"_L1;
515 quickBeginDeferred(this, name, m_fallbackStyle);
516 if (complete)
517 quickCompleteDeferred(this, name, m_fallbackStyle);
518}
519
520void QQStyleKitStyle::syncFromQPalette(const QPalette &palette)
521{
522 if (m_isUpdatingPalette)
523 return;
524 QScopedValueRollback<bool> rb(m_isUpdatingPalette, true);
525 if (palette == m_effectivePalette)
526 return;
527 m_effectivePalette = palette;
528 m_paletteProxy->fromQPalette(m_effectivePalette);
529 emit paletteChanged();
530}
531
532QPalette QQStyleKitStyle::effectivePalette() const
533{
534 return m_effectivePalette;
535}
536
537void QQStyleKitStyle::componentComplete()
538{
539 Q_ASSERT(!m_completed);
540 QQStyleKitControls::componentComplete();
541
542 executeFallbackStyle(true);
543 parseThemes();
544 recreateTheme();
545
546 /* It's important to set m_completed to true before resetting the readers, otherwise
547 * QQStyleKitStyle::loaded() will still be false, which will cause property reads to
548 * trigger the "skip read" optimization from QQStyleKitPropertyResolver */
549 m_completed = true;
550 reapplyStyle();
551}
552
553QT_END_NAMESPACE
554
555#include "moc_qqstylekitstyle_p.cpp"
Combined button and popup list for selecting options.
static const QString kDark
static const QString kLight
static QT_BEGIN_NAMESPACE const QString kSystem
\qmltype Style \inqmlmodule Qt.labs.StyleKit \inherits AbstractStyle