Debian Codegraph @

libs/CCAppCommon/QDarkStyleSheet/qdarkstyle/__init__.py

raw
1 # -*- coding: utf-8 -*-
2
3 """The most complete dark/light style sheet for Qt applications (Qt4, Qt5,
4 PySide, PySide2, PyQt4, PySide6, PyQt5, PyQt6, QtPy, PyQtGraph, Qt.Py) for
5 Python 2/3 and C++.
6
7 Python 2, as well as Qt4 (PyQt4 and PySide), will not be supported anymore.
8 They are still there as it is, but no back-compatibility, fixes, nor features
9 will be implemented.
10
11
12 Check the `documentation <https://qdarkstylesheet.readthedocs.io/en/stable>`__
13 to see how to set the desirable theme palette.
14
15 This module provides a function to load the stylesheets transparently
16 with the right resources file.
17
18 First, start importing our module
19
20 .. code-block:: python
21
22 import qdarkstyle
23
24 Then you can get the stylesheet provided by QDarkStyle for various Qt wrappers
25 as shown below
26
27 .. code-block:: python
28
29 # PySide 2
30 dark_stylesheet = qdarkstyle.load_stylesheet_pyside2()
31 # PyQt5
32 dark_stylesheet = qdarkstyle.load_stylesheet_pyqt5()
33 # PySide 6
34 dark_stylesheet = qdarkstyle.load_stylesheet_pyside6()
35 # PyQt6
36 dark_stylesheet = qdarkstyle.load_stylesheet_pyqt6()
37
38 Alternatively, from environment variables provided by QtPy, PyQtGraph, Qt.Py
39
40 .. code-block:: python
41
42 # QtPy
43 dark_stylesheet = qdarkstyle.load_stylesheet()
44 # PyQtGraph
45 dark_stylesheet = qdarkstyle.load_stylesheet(qt_api=os.environ('PYQTGRAPH_QT_LIB'))
46 # Qt.Py
47 dark_stylesheet = qdarkstyle.load_stylesheet(qt_api=Qt.__binding__)
48
49 Finally, set your QApplication with it
50
51 .. code-block:: python
52
53 app.setStyleSheet(dark_stylesheet)
54
55 Enjoy!
56
57 """
58
59 # Standard library imports
60 import logging
61 import os
62 import platform
63 import sys
64 import warnings
65
66 # Local imports
67 from qdarkstyle.dark.palette import DarkPalette
68 from qdarkstyle.light.palette import LightPalette
69 from qdarkstyle.palette import Palette
70
71 __version__ = "3.2.3"
72
73 _logger = logging.getLogger(__name__)
74
75 # Base directory paths
76 REPO_PATH = os.path.dirname(os.path.abspath(os.path.dirname(__file__)))
77 EXAMPLE_PATH = os.path.join(REPO_PATH, 'example')
78 IMAGES_PATH = os.path.join(REPO_PATH, 'docs', 'images')
79 PACKAGE_PATH = os.path.join(REPO_PATH, 'qdarkstyle')
80 QSS_PATH = os.path.join(PACKAGE_PATH, 'qss')
81 SVG_PATH = os.path.join(PACKAGE_PATH, 'svg')
82
83 # File names
84 MAIN_SCSS_FILE = 'main.scss'
85 STYLES_SCSS_FILE = '_styles.scss'
86 VARIABLES_SCSS_FILE = '_variables.scss'
87
88 # Prefixes and suffixes
89 RESOURCE_PREFIX = "qss_icons"
90 STYLE_PREFIX = "qdarkstyle"
91 QSS_FILE_SUFFIX = 'style.qss'
92 QRC_FILE_SUFFIX = 'style.qrc'
93
94 DEPRECATION_MSG = '''This function will be deprecated in v4.0.
95 Please, set the wanted binding by using QtPy environment variable QT_API,
96 then use load_stylesheet() passing the argument qt_api='wanted_binding'.'''
97
98 DEPRECATION_MSG_UNSUPPORTED = '''PyQt4/PySide use will be deprecated in v4.0,
99 by the lack of support. We will follow the minimum requirements given by QtPy,
100 project since QDarkStyle is dependent on it.'''
101
102
103 def _apply_os_patches(palette):
104 """
105 Apply OS-only specific stylesheet patches.
106
107 Returns:
108 str: stylesheet string (css).
109 """
110 os_fix = ""
111
112 if platform.system().lower() == 'darwin':
113 # See issue #12, #267
114 os_fix = '''
115 QDockWidget::title
116 {{
117 background-color: {color};
118 text-align: center;
119 height: 12px;
120 }}
121 QTabBar::close-button {{
122 padding: 2px;
123 }}
124 '''.format(color=palette.COLOR_BACKGROUND_4)
125
126 # Only open the QSS file if any patch is needed
127 if os_fix:
128 _logger.info("Found OS patches to be applied.")
129
130 return os_fix
131
132
133 def _apply_binding_patches():
134 """
135 Apply binding-only specific stylesheet patches for the same OS.
136
137 Returns:
138 str: stylesheet string (css).
139 """
140 binding_fix = ""
141
142 if binding_fix:
143 _logger.info("Found binding patches to be applied.")
144
145 return binding_fix
146
147
148 def _apply_version_patches(qt_version):
149 """
150 Apply version-only specific stylesheet patches for the same binding.
151
152 Args:
153 qt_version (str): Qt string version.
154
155 Returns:
156 str: stylesheet string (css).
157 """
158 version_fix = ""
159
160 major, minor, patch = qt_version.split('.')
161 major, minor, patch = int(major), int(minor), int(patch)
162
163 if major == 5 and minor >= 14:
164 # See issue #214
165 version_fix = '''
166 QMenu::item {
167 padding: 4px 24px 4px 6px;
168 }
169 '''
170
171 if version_fix:
172 _logger.info("Found version patches to be applied.")
173
174 return version_fix
175
176
177 def _apply_application_patches(QCoreApplication, QPalette, QColor, palette):
178 """
179 Apply application-level fixes on the QPalette.
180
181 The import names args must be passed here because the import is done
182 inside the load_stylesheet() function, as QtPy is only imported in
183 that moment for setting reasons.
184 """
185 # See issue #139
186 color = palette.COLOR_ACCENT_3
187 qcolor = QColor(color)
188
189 # Todo: check if it is qcoreapplication indeed
190 app = QCoreApplication.instance()
191
192 _logger.info("Found application patches to be applied.")
193
194 if app:
195 app_palette = app.palette()
196 app_palette.setColor(QPalette.Normal, QPalette.Link, qcolor)
197 app.setPalette(app_palette)
198 else:
199 _logger.warning("No QCoreApplication instance found. "
200 "Application patches not applied. "
201 "You have to call load_stylesheet function after "
202 "instantiation of QApplication to take effect. ")
203
204
205 def _load_stylesheet(qt_api='', palette=None):
206 """
207 Load the stylesheet based on QtPy abstraction layer environment variable.
208
209 If the argument is not passed, it uses the current QT_API environment
210 variable to make the imports of Qt bindings. If passed, it sets this
211 variable and then makes the imports.
212
213 Args:
214 qt_api (str): qt binding name to set QT_API environment variable.
215 Default is ''. Possible values are pyside, pyside2
216 pyqt4, pyqt5. Not case sensitive.
217 palette (Palette): Palette class that inherits from Palette.
218
219 Note:
220 - Note that the variable QT_API is read when first imported. So,
221 pay attention to the import order.
222 - If you are using another abstraction layer, i.e PyQtGraph to do
223 imports on Qt things you must set both to use the same Qt
224 binding (PyQt, PySide).
225 - OS, binding and binding version number, and application-specific
226 patches are applied in this order.
227
228 Returns:
229 str: stylesheet string (css).
230 """
231
232 if qt_api:
233 os.environ['QT_API'] = qt_api
234
235 # Import is made after setting QT_API
236 from qtpy.QtCore import QCoreApplication, QFile, QTextStream
237 from qtpy.QtGui import QColor, QPalette
238 from qtpy import QT_VERSION
239
240 # Then we import resources - binary qrc content
241 if palette is None:
242 from qdarkstyle.dark import darkstyle_rc # noqa
243 palette = DarkPalette
244 elif palette.ID == 'dark':
245 from qdarkstyle.dark import darkstyle_rc # noqa
246 palette = DarkPalette
247 elif palette.ID == 'light':
248 from qdarkstyle.light import lightstyle_rc # noqa
249 palette = LightPalette
250 else:
251 print("Not recognized ID for palette! Exiting!")
252 sys.exit(1)
253
254 # Thus, by importing the binary we can access the resources
255 package_dir = os.path.basename(PACKAGE_PATH)
256 palette_dir = os.path.join(package_dir, palette.ID)
257 qss_rc_path = ":" + os.path.join(palette_dir, palette.ID + QSS_FILE_SUFFIX)
258
259 _logger.debug(f"Reading QSS file in: {qss_rc_path}")
260
261 # It gets the qss file from compiled style_rc that was imported,
262 # not from the file QSS as we are using resources
263 qss_file = QFile(qss_rc_path)
264
265 if qss_file.exists():
266 qss_file.open(QFile.ReadOnly | QFile.Text)
267 text_stream = QTextStream(qss_file)
268 stylesheet = text_stream.readAll()
269 _logger.info("QSS file successfully loaded.")
270 else:
271 stylesheet = ""
272 # Todo: check this raise type and add to docs
273 raise FileNotFoundError("Unable to find QSS file '{}' "
274 "in resources.".format(qss_rc_path))
275
276 _logger.debug("Checking patches for being applied.")
277
278 # Todo: check execution order for these functions
279 # 1. Apply OS specific patches
280 stylesheet += _apply_os_patches(palette)
281
282 # 2. Apply binding specific patches
283 stylesheet += _apply_binding_patches()
284
285 # 3. Apply binding version specific patches
286 stylesheet += _apply_version_patches(QT_VERSION)
287
288 # 4. Apply palette fix. See issue #139
289 _apply_application_patches(QCoreApplication, QPalette, QColor, palette)
290
291 return stylesheet
292
293
294 def load_stylesheet(*args, **kwargs):
295 """
296 Load the stylesheet. Takes care of importing the rc module.
297
298 Args:
299 pyside (bool): True to load the PySide (or PySide2) rc file,
300 False to load the PyQt4 (or PyQt5) rc file.
301 Default is False.
302 or
303
304 qt_api (str): Qt binding name to set QT_API environment variable.
305 Default is '', i.e PyQt5 the default QtPy binding.
306 Possible values are pyside, pyside2 pyqt4, pyqt5.
307 Not case sensitive.
308
309 or
310
311 palette (Palette): Class (not instance) that inherits from Palette.
312
313 Raises:
314 TypeError: If arguments do not match: type, keyword name nor quantity.
315
316 Returns:
317 str: the stylesheet string.
318 """
319
320 stylesheet = ""
321 arg = None
322
323 try:
324 arg = args[0]
325 except IndexError:
326 # It is already none
327 pass
328
329 # Get palette
330 palette = kwargs.get('palette', None)
331
332 # Number of arguments are wrong
333 if (kwargs and args) or len(args) > 2 or len(kwargs) > 2:
334 raise TypeError("load_stylesheet() takes zero, one or two arguments: "
335 "(new) string type qt_api='pyqt5' or "
336 "(old) boolean type pyside='False' or "
337 "(new) palette type palette=Palette.")
338
339 # No arguments
340 if not kwargs and not args:
341 stylesheet = _load_stylesheet(qt_api='pyqt5')
342
343 # Old API arguments
344 elif 'pyside' in kwargs or isinstance(arg, bool):
345 pyside = kwargs.get('pyside', arg)
346
347 if pyside:
348 stylesheet = _load_stylesheet(qt_api='pyside2', palette=palette)
349 if not stylesheet:
350 stylesheet = _load_stylesheet(qt_api='pyside', palette=palette)
351
352 else:
353 stylesheet = _load_stylesheet(qt_api='pyqt5', palette=palette)
354 if not stylesheet:
355 stylesheet = _load_stylesheet(qt_api='pyqt4', palette=palette)
356
357 # Deprecation warning only for old API
358 warnings.warn(DEPRECATION_MSG, DeprecationWarning)
359
360 # New API arguments
361 elif 'qt_api' in kwargs or isinstance(arg, str):
362 qt_api = kwargs.get('qt_api', arg)
363 stylesheet = _load_stylesheet(qt_api=qt_api, palette=palette)
364
365 # Palette arg
366 elif 'palette' in kwargs or issubclass(arg, Palette):
367 palette_arg = kwargs.get('palette', arg)
368 stylesheet = _load_stylesheet(palette=palette_arg)
369
370 # Wrong API arguments name or type
371 else:
372 raise TypeError("load_stylesheet() takes only zero, one or two arguments: "
373 "(new) string type qt_api='pyqt5' or "
374 "(new) palette type palette=Palette or "
375 "(old) boolean type pyside='False'.")
376
377 return stylesheet
378
379
380 def load_stylesheet_pyside():
381 """
382 Load the stylesheet for use in a PySide application.
383
384 Returns:
385 str: the stylesheet string.
386 """
387 return _load_stylesheet(qt_api='pyside')
388
389
390 def load_stylesheet_pyside2():
391 """
392 Load the stylesheet for use in a PySide2 application.
393
394 Returns:
395 str: the stylesheet string.
396 """
397 return _load_stylesheet(qt_api='pyside2')
398
399
400 def load_stylesheet_pyside6():
401 """
402 Load the stylesheet for use in a PySide6 application.
403
404 Returns:
405 str: the stylesheet string.
406 """
407 return _load_stylesheet(qt_api='pyside6')
408
409
410 def load_stylesheet_pyqt():
411 """
412 Load the stylesheet for use in a PyQt4 application.
413
414 Returns:
415 str: the stylesheet string.
416 """
417 return _load_stylesheet(qt_api='pyqt4')
418
419
420 def load_stylesheet_pyqt5():
421 """
422 Load the stylesheet for use in a PyQt5 application.
423
424 Returns:
425 str: the stylesheet string.
426 """
427 return _load_stylesheet(qt_api='pyqt5')
428
429
430 def load_stylesheet_pyqt6():
431 """
432 Load the stylesheet for use in a PyQt6 application.
433
434 Returns:
435 str: the stylesheet string.
436 """
437 return _load_stylesheet(qt_api='pyqt6')
438
439
440 # Deprecation Warning --------------------------------------------------------
441
442
443 def load_stylesheet_from_environment(is_pyqtgraph=False):
444 """
445 Load the stylesheet from QT_API (or PYQTGRAPH_QT_LIB) environment variable.
446
447 Args:
448 is_pyqtgraph (bool): True if it is to be set using PYQTGRAPH_QT_LIB.
449
450 Raises:
451 KeyError: if PYQTGRAPH_QT_LIB does not exist.
452
453 Returns:
454 str: the stylesheet string.
455 """
456 warnings.warn(DEPRECATION_MSG, DeprecationWarning)
457
458 if is_pyqtgraph:
459 stylesheet = _load_stylesheet(qt_api=os.environ.get('PYQTGRAPH_QT_LIB', None))
460 else:
461 stylesheet = _load_stylesheet()
462
463 return stylesheet
464
465
466 # Deprecated ----------------------------------------------------------------