Debian Codegraph @

libs/CCAppCommon/QDarkStyleSheet/qdarkstyle/example/__main__.py

raw
1 #!/usr/bin/env python3
2 # -*- coding: utf-8 -*-
3
4 """Example of qdarkstyle use for Python and Qt applications.
5
6 This module a main window with every item that could be created with
7 Qt Design (common ones) in the basic states (enabled/disabled), and
8 (checked/unchecked) for those who has this attribute.
9
10 Requirements:
11
12 - Python 3
13 - QtPy
14 - PyQt6 or PyQt5 or PyQt4 or PySide6 or PySide2 or PySide
15 - PyQtGraph or Qt.Py (if chosen)
16
17 To run this example using PyQt5, simple do
18
19 .. code-block:: python
20
21 python example.py
22
23 or
24
25 .. code-block:: python
26
27 python example.py --qt_from=pyqt5
28
29 Other options for qt_from are: pyqt6, pyqt5, pyside6, pyside2, pyqt, pyside,
30 qtpy, pyqtgraph, and qt.py.
31
32 Also, you can run the example without any theme (none), to check for problems.
33
34 .. code-block:: python
35
36 python example.py --qt_from=pyqt5 --palette=none
37
38 Note:
39 qdarkstyle does not have to be installed to run the example.
40
41 """
42
43 # Standard library imports
44
45 import argparse
46 import logging
47 import os
48 import sys
49 import platform
50 import time
51
52 # Make the example runnable without the need to install and include ui
53 sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../..'))
54 sys.path.insert(0, os.path.abspath(os.path.dirname(os.path.abspath(__file__)) + '/../ui'))
55
56 # Must be in this place, after setting path, to not need to install
57 import qdarkstyle # noqa: E402
58 from qdarkstyle.dark.palette import DarkPalette # noqa: E402
59 from qdarkstyle.light.palette import LightPalette # noqa: E402
60
61 # Set log for debug
62 logging.basicConfig(level=logging.INFO)
63 _logger = logging.getLogger(__name__)
64
65 here = os.path.abspath(os.path.dirname(__file__))
66
67 # Constants
68 SCREENSHOTS_PATH = qdarkstyle.IMAGES_PATH
69
70
71 def main():
72 """Execute QDarkStyle example."""
73 parser = argparse.ArgumentParser(description=__doc__,
74 formatter_class=argparse.RawDescriptionHelpFormatter)
75 parser.add_argument('--palette', default='dark', type=str,
76 choices=['dark', 'light', 'none'],
77 help="Palette to display. Using 'none' there is no style sheet applied, OS like.")
78 parser.add_argument('--qt_from', default='pyqt5', type=str,
79 choices=['pyqt6', 'pyqt5', 'pyqt', 'pyside6', 'pyside2', 'pyside', 'qtpy', 'pyqtgraph', 'qt.py'],
80 help="Choose which binding and/or abstraction is to be used to run the example. Default is 'qtpy'")
81 parser.add_argument('--test', action='store_true',
82 help="Auto close window after 2s.")
83 parser.add_argument('--screenshots', action='store_true',
84 help="Generate screenshots on images folder.")
85 parser.add_argument('--offscreen', action='store_true',
86 help="Do not try to show the screen (running on server).")
87 parser.add_argument('--reset', action='store_true',
88 help="Reset GUI settings (position, size) then opens.")
89
90 # Parsing arguments from command line
91 args = parser.parse_args()
92
93 # To avoid problems when testing without screen
94 if args.test or args.offscreen:
95 os.environ['QT_QPA_PLATFORM'] = 'offscreen'
96
97 # Set QT_API variable before importing QtPy
98 if args.qt_from in ['pyqt', 'pyqt5', 'pyqt6', 'pyside', 'pyside2', 'pyside6']:
99 os.environ['QT_API'] = args.qt_from
100 elif args.qt_from == 'pyqtgraph':
101 os.environ['QT_API'] = os.environ['PYQTGRAPH_QT_LIB']
102 elif args.qt_from in ['qt.py', 'qt']:
103 try:
104 import Qt
105 except ImportError:
106 print('Could not import Qt (Qt.Py)')
107 else:
108 os.environ['QT_API'] = Qt.__binding__
109
110 # QtPy imports
111 from qtpy import API_NAME, QT_VERSION, PYQT_VERSION, PYSIDE_VERSION, uic
112 from qtpy import __version__ as QTPY_VERSION
113 from qtpy import QtCore, QtGui, QtWidgets
114
115 # Set API_VERSION variable
116 API_VERSION = ''
117
118 if PYQT_VERSION:
119 API_VERSION = PYQT_VERSION
120 elif PYSIDE_VERSION:
121 API_VERSION = PYSIDE_VERSION
122 else:
123 API_VERSION = 'Not found'
124
125 # create the application
126 app = QtWidgets.QApplication(sys.argv)
127 app.setOrganizationName('QDarkStyle')
128 app.setApplicationName('QDarkStyle Example')
129
130 style = ''
131
132 if args.palette == 'dark':
133 style = qdarkstyle.load_stylesheet(palette=DarkPalette)
134 elif args.palette == 'light':
135 style = qdarkstyle.load_stylesheet(palette=LightPalette)
136
137 app.setStyleSheet(style)
138
139 # create main window
140 window = QtWidgets.QMainWindow()
141 window.setObjectName('mainwindow')
142 uic.loadUi(os.path.join(here, 'ui/mw_menus.ui'), window)
143
144 title = ("QDarkStyle Example - ("
145 + f"Palette={args.palette}, "
146 + f"QDarkStyle=v{qdarkstyle.__version__}, "
147 + f"QtPy=v{QTPY_VERSION}, "
148 + f"{API_NAME}=v{API_VERSION}, "
149 + f"Qt=v{QT_VERSION}, "
150 + f"Python=v{platform.python_version()}, "
151 # Operating system info are maybe too much,
152 # but different OS add info in different places
153 + f"System={platform.system()}, "
154 + f"Release={platform.release()}, "
155 + f"Version={platform.version()}, "
156 + f"Platform={platform.platform()}"
157 + ")")
158
159 _logger.info(title)
160 window.setWindowTitle(title)
161
162 # Create docks for buttons
163 dw_buttons = QtWidgets.QDockWidget()
164 dw_buttons.setObjectName('buttons')
165 uic.loadUi(os.path.join(here, 'ui/dw_buttons.ui'), dw_buttons)
166 window.addDockWidget(QtCore.Qt.RightDockWidgetArea, dw_buttons)
167
168 # Set state indeterminate #275
169 dw_buttons.checkBoxTristate.stateChanged.connect(dw_buttons.checkBoxTristateDis.setCheckState)
170 dw_buttons.checkBoxTristate.setCheckState(QtCore.Qt.PartiallyChecked)
171
172 # Add actions on popup toolbuttons
173 menu = QtWidgets.QMenu()
174
175 for action in ['Action A', 'Action B', 'Action C']:
176 menu.addAction(action)
177
178 # Add menu in special tool buttons
179 dw_buttons.toolButtonDelayedPopup.setMenu(menu)
180 dw_buttons.toolButtonInstantPopup.setMenu(menu)
181 dw_buttons.toolButtonMenuButtonPopup.setMenu(menu)
182
183 # Add menu in toolbar #251
184 action_menu = QtWidgets.QAction(u'Menu action', window.toolBarMenus)
185 action_menu.setMenu(menu)
186 window.toolBarMenus.addAction(action_menu)
187
188 # Add color to tab title text #212
189 window.tabWidget.tabBar().setTabTextColor(3, QtGui.QColor('red'))
190
191 # Connect dialogs to buttons
192 window.toolButtonColorDialog.clicked.connect(lambda: QtWidgets.QColorDialog().exec())
193 window.toolButtonFileDialog.clicked.connect(lambda: QtWidgets.QFileDialog().exec())
194 window.toolButtonFileDialogStatic.clicked.connect(lambda: QtWidgets.QFileDialog.getOpenFileNames())
195 window.toolButtonFontDialog.clicked.connect(lambda: QtWidgets.QFontDialog().exec())
196 window.toolButtonInputDialog.clicked.connect(lambda: QtWidgets.QInputDialog().exec())
197 window.toolButtonMessageBox.clicked.connect(lambda: QtWidgets.QMessageBox().exec())
198 window.toolButtonMessageBoxStatic.clicked.connect(lambda: QtWidgets.QMessageBox.critical(window, "Critical title", "Critical message"))
199 window.toolButtonProgressDialog.clicked.connect(lambda: QtWidgets.QProgressDialog().exec())
200
201 # Create docks for buttons
202 dw_displays = QtWidgets.QDockWidget()
203 dw_displays.setObjectName('displays')
204 uic.loadUi(os.path.join(here, 'ui/dw_displays.ui'), dw_displays)
205 window.addDockWidget(QtCore.Qt.RightDockWidgetArea, dw_displays)
206
207 # Create docks for inputs - no fields
208 dw_inputs_no_fields = QtWidgets.QDockWidget()
209 dw_inputs_no_fields.setObjectName('inputs_no_fields')
210 uic.loadUi(os.path.join(here, 'ui/dw_inputs_no_fields.ui'), dw_inputs_no_fields)
211 window.addDockWidget(QtCore.Qt.RightDockWidgetArea, dw_inputs_no_fields)
212
213 # Create docks for inputs - fields
214 dw_inputs_fields = QtWidgets.QDockWidget()
215 dw_inputs_fields.setObjectName('inputs_fields')
216 uic.loadUi(os.path.join(here, 'ui/dw_inputs_fields.ui'), dw_inputs_fields)
217 window.addDockWidget(QtCore.Qt.RightDockWidgetArea, dw_inputs_fields)
218
219 # Create docks for widgets
220 dw_widgets = QtWidgets.QDockWidget()
221 dw_widgets.setObjectName('widgets')
222 uic.loadUi(os.path.join(here, 'ui/dw_widgets.ui'), dw_widgets)
223 window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dw_widgets)
224
225 # Create docks for views
226 dw_views = QtWidgets.QDockWidget()
227 dw_views.setObjectName('views')
228 uic.loadUi(os.path.join(here, 'ui/dw_views.ui'), dw_views)
229 window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dw_views)
230
231 # Create docks for containers - no tabs
232 dw_containers_no_tabs = QtWidgets.QDockWidget()
233 dw_containers_no_tabs.setObjectName('containers_no_tabs')
234 uic.loadUi(os.path.join(here, 'ui/dw_containers_no_tabs.ui'), dw_containers_no_tabs)
235 window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dw_containers_no_tabs)
236
237 # Create docks for containters - tabs
238 dw_containers_tabs = QtWidgets.QDockWidget()
239 dw_containers_tabs.setObjectName('containers_tabs')
240 uic.loadUi(os.path.join(here, 'ui/dw_containers_tabs.ui'), dw_containers_tabs)
241 window.addDockWidget(QtCore.Qt.LeftDockWidgetArea, dw_containers_tabs)
242
243 # Tabify right docks
244 window.tabifyDockWidget(dw_buttons, dw_displays)
245 window.tabifyDockWidget(dw_displays, dw_inputs_fields)
246 window.tabifyDockWidget(dw_inputs_fields, dw_inputs_no_fields)
247
248 # Tabify left docks
249 window.tabifyDockWidget(dw_containers_no_tabs, dw_containers_tabs)
250 window.tabifyDockWidget(dw_containers_tabs, dw_widgets)
251 window.tabifyDockWidget(dw_widgets, dw_views)
252
253 # Issues #9120, #9121 on Spyder
254 qstatusbar = QtWidgets.QStatusBar()
255 qstatusbar.addWidget(QtWidgets.QLabel('Issue Spyder #9120, #9121 - background not matching.'))
256 qstatusbar.addWidget(QtWidgets.QPushButton('OK'))
257
258 # Add info also in status bar for screenshots get it
259 qstatusbar.addWidget(QtWidgets.QLabel('INFO: ' + title))
260 window.setStatusBar(qstatusbar)
261
262 # Todo: add report info and other info in HELP graphical
263
264 # Auto quit after 2s when in test mode
265 if args.test:
266 QtCore.QTimer.singleShot(2000, app.exit)
267
268 # Save screenshots for different displays and quit
269 if args.screenshots:
270 window.showFullScreen()
271 create_screenshots(app, window, args)
272 # Do not read settings when taking screenshots - like reset
273 else:
274 _read_settings(window, args.reset, QtCore.QSettings)
275 window.showMaximized()
276
277 app.exec_()
278 _write_settings(window, QtCore.QSettings)
279
280
281 def _write_settings(window, QSettingsClass):
282 """Get window settings and write it into a file."""
283 settings = QSettingsClass('QDarkStyle', 'QDarkStyle Example')
284 settings.setValue('pos', window.pos())
285 settings.setValue('size', window.size())
286 settings.setValue('state', window.saveState())
287
288
289 def _read_settings(window, reset, QSettingsClass):
290 """Read and set window settings from a file."""
291 settings = QSettingsClass('QDarkStyle', 'QDarkStyle Example')
292
293 try:
294 pos = settings.value('pos', window.pos())
295 size = settings.value('size', window.size())
296 state = settings.value('state', window.saveState())
297 except Exception:
298 pos = settings.value('pos', window.pos(), type='QPoint')
299 size = settings.value('size', window.size(), type='QSize')
300 state = settings.value('state', window.saveState(), type='QByteArray')
301
302 if not reset:
303 window.restoreState(state)
304 window.resize(size)
305 window.move(pos)
306
307
308 def create_screenshots(app, window, args):
309 """Save screenshots for different application views and quit."""
310
311 theme = args.palette
312
313 print('\nCreating {} screenshots'.format(theme))
314
315 docks = window.findChildren(QtWidgets.QDockWidget)
316 tabs = window.findChildren(QtWidgets.QTabWidget)
317
318 widget_data = {
319 'containers_no_tabs_buttons.png': [
320 'Containers - No Tabs',
321 'Buttons',
322 ],
323 'containers_tabs_displays.png': [
324 'Containers - Tabs',
325 'Displays',
326 ],
327 'widgets_inputs_fields.png': [
328 'Widgets',
329 'Inputs - Fields',
330 ],
331 'views_inputs_no_fields.png': [
332 'Views',
333 'Inputs - No Fields',
334 ]
335 }
336
337 # Central widget tabs of with examples, reset positions
338 tab = [tab for tab in tabs if tab.count() >= 12][0]
339 tab.setCurrentIndex(0)
340
341 QtCore.QCoreApplication.processEvents()
342
343 for fname_suffix, dw_titles in widget_data.items():
344 png_path = os.path.join(SCREENSHOTS_PATH, theme, fname_suffix)
345 print('\t' + png_path)
346
347 for dw in docks:
348 if dw.windowTitle() in dw_titles:
349 print('Evidencing : ', dw.windowTitle())
350 dw.raise_()
351 dw.show()
352 QtCore.QCoreApplication.processEvents()
353
354 # Attention: any change in update, processEvent and sleep calls
355 # make those screenshots not working, specially the first one.
356 # It seems that processEvents are not working properly
357
358 window.update()
359 window.showFullScreen()
360 QtCore.QCoreApplication.processEvents()
361
362 time.sleep(0.5)
363 QtCore.QCoreApplication.processEvents()
364
365 screen = QtGui.QGuiApplication.primaryScreen()
366 QtCore.QCoreApplication.processEvents()
367 pixmap = screen.grabWindow(window.winId())
368
369 # Yeah, this is duplicated to avoid screenshot problems
370 screen = QtGui.QGuiApplication.primaryScreen()
371 QtCore.QCoreApplication.processEvents()
372 pixmap = screen.grabWindow(window.winId())
373
374 img = pixmap.toImage()
375 img.save(png_path)
376
377 QtCore.QCoreApplication.processEvents()
378
379 QtCore.QCoreApplication.processEvents()
380 window.close()
381 print('\n')
382 app.exit(sys.exit())
383
384
385 if __name__ == "__main__":
386 sys.exit(main())