def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasQTAgg(figure) manager = FigureManagerWorkbench(canvas, num) return manager if __name__ == '__main__': # testing code import numpy as np qapp = QApplication([' ']) qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) if hasattr(Qt, 'AA_EnableHighDpiScaling'): qapp.setAttribute(Qt.AA_EnableHighDpiScaling, True) x = np.linspace(0, 10*np.pi, 1000) cx, sx = np.cos(x), np.sin(x) fig_mgr_1 = new_figure_manager(1) fig1 = fig_mgr_1.canvas.figure ax = fig1.add_subplot(111) ax.set_title("Test title") ax.set_xlabel("$\mu s$") ax.set_ylabel("Counts") ax.plot(x, cx) fig1.show() qapp.exec_()
def opensesame(): import os, sys, platform # Add the folder that contains the OpenSesame modules to the path. This is # generally only necessary if OpenSesame is directly run from source, # instead from an installation. if os.path.exists(os.path.join(os.getcwd(), 'libopensesame')): sys.path.insert(0, os.getcwd()) # Support for multiprocessing when packaged # In OS X the multiprocessing module is horribly broken, but a fixed # version has been released as the 'billiard' module if platform.system() == 'Darwin': # Use normal multirpocessing module from python 3.4 and on if sys.version_info >= (3,4): from multiprocessing import freeze_support, set_start_method freeze_support() set_start_method('forkserver') else: from billiard import freeze_support, forking_enable freeze_support() forking_enable(0) else: from multiprocessing import freeze_support freeze_support() # Parse the (optional) environment file that contains special paths, etc. from libopensesame.misc import resource, filesystem_encoding, \ parse_environment_file parse_environment_file() # Force the new-style Qt API import sip import qtpy sip.setapi('QString', 2) sip.setapi('QVariant', 2) # Load debug package (this must be after the working directory change) from libopensesame import debug # Do the basic window initialization from qtpy.QtWidgets import QApplication # From Qt 5.6 on, QtWebEngine is the default way to render web pages # QtWebEngineWidgets must be imported before a QCoreApplication instance is # created. try: from qtpy import QtWebEngineWidgets except ImportError: pass app = QApplication(sys.argv) # Enable High DPI display with PyQt5 if hasattr(qtpy.QtCore.Qt, 'AA_UseHighDpiPixmaps'): app.setAttribute(qtpy.QtCore.Qt.AA_UseHighDpiPixmaps) from libqtopensesame.qtopensesame import qtopensesame opensesame = qtopensesame(app) opensesame.__script__ = __file__ app.processEvents() # Install the translator. For some reason, the translator needs to be # instantiated here and not in the set_locale() function, otherwise the # locale is ignored. from qtpy.QtCore import QTranslator translator = QTranslator() opensesame.set_locale(translator) # Now that the window is shown, load the remaining modules and resume the # GUI initialization. opensesame.resume_init() opensesame.restore_window_state() opensesame.refresh() opensesame.show() # Added for OS X, otherwise Window will not appear opensesame.raise_() # Exit using the application exit status sys.exit(app.exec_())
def __init__(self, sys_argv): super().__init__() self.__m_vtkFboItem = None #sys_argv += ['--style', 'Material'] #! MUST HAVE #sys_argv += ['--style', 'Fusion'] #! MUST HAVE sys_argv += ['--style', 'Windows'] #! MUST HAVE QApplication.setAttribute(Qt.AA_UseDesktopOpenGL) QtGui.QSurfaceFormat.setDefaultFormat( defaultFormat(False)) # from vtk 8.2.0 app = QApplication(sys_argv) app.setApplicationName("QtQuickVTK") app.setWindowIcon(QIcon(":/resources/bq.ico")) app.setOrganizationName("Sexy Soft") app.setOrganizationDomain("www.sexysoft.com") engine = QQmlApplicationEngine() app.setApplicationName('QtVTK-Py') # Register QML Types qmlRegisterType(FboItem, 'QtVTK', 1, 0, 'VtkFboItem') # Expose/Bind Python classes (QObject) to QML ctxt = engine.rootContext() # returns QQmlContext ctxt.setContextProperty('canvasHandler', self) self.dataProvider = ChartDataProvider() ctxt.setContextProperty('chartDataProvider', self.dataProvider) # Load main QML file engine.load(QUrl.fromLocalFile('resources/main.qml')) # Get reference to the QVTKFramebufferObjectItem in QML rootObject = engine.rootObjects()[0] # returns QObject self.__m_vtkFboItem = rootObject.findChild(FboItem, 'vtkFboItem') # Give the vtkFboItem reference to the CanvasHandler if (self.__m_vtkFboItem): qDebug( 'CanvasHandler::CanvasHandler: setting vtkFboItem to CanvasHandler' ) self.__m_vtkFboItem.rendererInitialized.connect( self.startApplication) else: qCritical( 'CanvasHandler::CanvasHandler: Unable to get vtkFboItem instance' ) return MySettings = QSettings() print("load Settings") self.fileDialog = rootObject.findChild(QObject, "myFileDialog") if (self.fileDialog is not None): tmp = MySettings.value(CanvasHandler.DEFAULT_MODEL_DIR_KEY) print(tmp) self.fileDialog.setProperty("folder", QUrl.fromLocalFile(tmp)) rc = app.exec_() qDebug( f'CanvasHandler::CanvasHandler: Execution finished with return code: {rc}' )
while changed: changed = False for edge in edges: source = edge.node_source dest = edge.node_dest if source in connected and dest not in connected: current.append(dest) changed = True if dest in connected and source not in connected: current.append(source) changed = True current = indirect connected.extend(current) return direct, indirect if __name__ == '__main__': import sys app = QApplication(sys.argv) app.setAttribute(Qt.AA_UseHighDpiPixmaps) from glue.core.state import load dc = load('links.glu') widget = DataGraphWidget(dc) widget.show() sys.exit(app.exec_())
while changed: changed = False for edge in edges: source = edge.node_source dest = edge.node_dest if source in connected and dest not in connected: current.append(dest) changed = True if dest in connected and source not in connected: current.append(source) changed = True current = indirect connected.extend(current) return direct, indirect if __name__ == '__main__': import sys app = QApplication(sys.argv) app.setAttribute(Qt.AA_UseHighDpiPixmaps) from glue.core.state import load dc = load('links.glu') widget = DataGraphWidget(dc) widget.show() sys.exit(app.exec_())
def new_figure_manager_given_figure(num, figure): """ Create a new figure manager instance for the given figure. """ canvas = FigureCanvasQTAgg(figure) manager = FigureManagerWorkbench(canvas, num) return manager if __name__ == '__main__': # testing code import numpy as np qapp = QApplication([' ']) qapp.setAttribute(Qt.AA_UseHighDpiPixmaps) if hasattr(Qt, 'AA_EnableHighDpiScaling'): qapp.setAttribute(Qt.AA_EnableHighDpiScaling, True) x = np.linspace(0, 10 * np.pi, 1000) cx, sx = np.cos(x), np.sin(x) fig_mgr_1 = new_figure_manager(1) fig1 = fig_mgr_1.canvas.figure ax = fig1.add_subplot(111) ax.set_title("Test title") ax.set_xlabel("$\mu s$") ax.set_ylabel("Counts") ax.plot(x, cx) fig1.show() qapp.exec_()
# This file is part of Frhodo. Copyright © 2020, UChicago Argonne, LLC # and licensed under BSD-3-Clause. See License.txt in the top-level # directory for license and copyright information. import os, sys from copy import deepcopy from qtpy.QtWidgets import QDialog, QApplication, QShortcut, QListWidget from qtpy import uic, QtCore, QtGui import numpy as np if os.environ[ 'QT_API'] == 'pyside2': # Silence warning: "Qt WebEngine seems to be initialized from a plugin." QApplication.setAttribute(QtCore.Qt.AA_ShareOpenGLContexts) # Handle high resolution displays: Minimum recommended resolution 1280 x 960 if hasattr(QtCore.Qt, 'AA_EnableHighDpiScaling'): QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) if hasattr(QtCore.Qt, 'AA_UseHighDpiPixmaps'): QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) class Save_Dialog(QDialog, QApplication): def __init__(self, parent): super().__init__() uic.loadUi(str(parent.path['main'] / 'UI' / 'save_dialog.ui'), self) self.parent = parent self.var = { 'comment': '',
import time from datetime import timedelta from random import choice # Third party imports from qtpy import QtCore from qtpy.QtCore import Signal, Slot from qtpy.QtGui import QFont, QPixmap, QIcon from qtpy.QtWidgets import (QMainWindow, QApplication, QLineEdit, QVBoxLayout, QWidget, QFrame, QLabel) import qdarkstyle VER = "0.0.01" # enable highdpi scaling QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) # use highdpi icons class VLine(QFrame): def __init__(self): super().__init__() self.setFrameShape(self.VLine | self.Sunken) class ManageTyping: """Typing 정보를 저장한다.""" def __init__(self): self.start_time = None # 이전 게임을 시작한 시간 self.elapsed_time_total = 0 # 전체 Typing 시간
def get_app( *, app_name: str = None, app_version: str = None, icon: str = None, org_name: str = None, org_domain: str = None, app_id: str = None, ipy_interactive: bool = None, ) -> QApplication: """Get or create the Qt QApplication. There is only one global QApplication instance, which can be retrieved by calling get_app again, (or by using QApplication.instance()) Parameters ---------- app_name : str, optional Set app name (if creating for the first time), by default 'napari' app_version : str, optional Set app version (if creating for the first time), by default __version__ icon : str, optional Set app icon (if creating for the first time), by default NAPARI_ICON_PATH org_name : str, optional Set organization name (if creating for the first time), by default 'napari' org_domain : str, optional Set organization domain (if creating for the first time), by default 'napari.org' app_id : str, optional Set organization domain (if creating for the first time). Will be passed to set_app_id (which may also be called independently), by default NAPARI_APP_ID ipy_interactive : bool, optional Use the IPython Qt event loop ('%gui qt' magic) if running in an interactive IPython terminal. Returns ------- QApplication [description] Notes ----- Substitutes QApplicationWithTracing when the NAPARI_PERFMON env variable is set. """ # napari defaults are all-or nothing. If any of the keywords are used # then they are all used. set_values = {k for k, v in locals().items() if v} kwargs = locals() if set_values else _defaults global _app_ref app = QApplication.instance() if app: set_values.discard("ipy_interactive") if set_values: warn( trans._( "QApplication already existed, these arguments to to 'get_app' were ignored: {args}", deferred=True, args=set_values, )) if perf_config and perf_config.trace_qt_events: warn( trans._( "Using NAPARI_PERFMON with an already-running QtApp (--gui qt?) is not supported.", deferred=True, )) else: # automatically determine monitor DPI. # Note: this MUST be set before the QApplication is instantiated if PYQT5: QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) argv = sys.argv.copy() if sys.platform == "darwin" and not argv[0].endswith("napari"): # Make sure the app name in the Application menu is `napari` # which is taken from the basename of sys.argv[0]; we use # a copy so the original value is still available at sys.argv argv[0] = "napari" if perf_config and perf_config.trace_qt_events: from .perf.qt_event_tracing import QApplicationWithTracing app = QApplicationWithTracing(argv) else: app = QApplication(argv) # if this is the first time the Qt app is being instantiated, we set # the name and metadata app.setApplicationName(kwargs.get('app_name')) app.setApplicationVersion(kwargs.get('app_version')) app.setOrganizationName(kwargs.get('org_name')) app.setOrganizationDomain(kwargs.get('org_domain')) set_app_id(kwargs.get('app_id')) # Intercept tooltip events in order to convert all text to rich text # to allow for text wrapping of tooltips app.installEventFilter(QtToolTipEventFilter()) if app.windowIcon().isNull(): app.setWindowIcon(QIcon(kwargs.get('icon'))) if ipy_interactive is None: ipy_interactive = get_settings().application.ipy_interactive if _IPYTHON_WAS_HERE_FIRST: _try_enable_ipython_gui('qt' if ipy_interactive else None) if not _ipython_has_eventloop(): notification_manager.notification_ready.connect( NapariQtNotification.show_notification) notification_manager.notification_ready.connect( show_console_notification) if perf_config and not perf_config.patched: # Will patch based on config file. perf_config.patch_callables() if not _app_ref: # running get_app for the first time # see docstring of `wait_for_workers_to_quit` for caveats on killing # workers at shutdown. app.aboutToQuit.connect(wait_for_workers_to_quit) # this will register all of our resources (icons) with Qt, so that they # can be used in qss files and elsewhere. _register_napari_resources() _app_ref = app # prevent garbage collection # Add the dispatcher attribute to the application to be able to dispatch # notifications coming from threads return app
def get_app( *, app_name: str = None, app_version: str = None, icon: str = None, org_name: str = None, org_domain: str = None, app_id: str = None, ipy_interactive: bool = None, ) -> QApplication: """Get or create the Qt QApplication. There is only one global QApplication instance, which can be retrieved by calling get_app again, (or by using QApplication.instance()) Parameters ---------- app_name : str, optional Set app name (if creating for the first time), by default 'napari' app_version : str, optional Set app version (if creating for the first time), by default __version__ icon : str, optional Set app icon (if creating for the first time), by default NAPARI_ICON_PATH org_name : str, optional Set organization name (if creating for the first time), by default 'napari' org_domain : str, optional Set organization domain (if creating for the first time), by default 'napari.org' app_id : str, optional Set organization domain (if creating for the first time). Will be passed to set_app_id (which may also be called independently), by default NAPARI_APP_ID ipy_interactive : bool, optional Use the IPython Qt event loop ('%gui qt' magic) if running in an interactive IPython terminal. Returns ------- QApplication [description] Notes ----- Substitutes QApplicationWithTracing when the NAPARI_PERFMON env variable is set. If the QApplication already exists, we call convert_app_for_tracing() which deletes the QApplication and creates a new one. However here with get_app we need to create the correct QApplication up front, or we will crash because we'd be deleting the QApplication after we created QWidgets with it, such as we do for the splash screen. """ # napari defaults are all-or nothing. If any of the keywords are used # then they are all used. set_values = {k for k, v in locals().items() if v} kwargs = locals() if set_values else _defaults global _app_ref app = QApplication.instance() if app: set_values.discard("ipy_interactive") if set_values: warn( trans._( "QApplication already existed, these arguments to to 'get_app' were ignored: {args}", deferred=True, args=set_values, )) if perf_config and perf_config.trace_qt_events: from .perf.qt_event_tracing import convert_app_for_tracing # no-op if app is already a QApplicationWithTracing app = convert_app_for_tracing(app) else: # automatically determine monitor DPI. # Note: this MUST be set before the QApplication is instantiated QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) if perf_config and perf_config.trace_qt_events: from .perf.qt_event_tracing import QApplicationWithTracing app = QApplicationWithTracing(sys.argv) else: app = QApplication(sys.argv) # if this is the first time the Qt app is being instantiated, we set # the name and metadata app.setApplicationName(kwargs.get('app_name')) app.setApplicationVersion(kwargs.get('app_version')) app.setOrganizationName(kwargs.get('org_name')) app.setOrganizationDomain(kwargs.get('org_domain')) set_app_id(kwargs.get('app_id')) if not _ipython_has_eventloop(): notification_manager.notification_ready.connect( NapariQtNotification.show_notification) notification_manager.notification_ready.connect( show_console_notification) if app.windowIcon().isNull(): app.setWindowIcon(QIcon(kwargs.get('icon'))) if ipy_interactive is None: ipy_interactive = get_settings().application.ipy_interactive _try_enable_ipython_gui('qt' if ipy_interactive else None) if perf_config and not perf_config.patched: # Will patch based on config file. perf_config.patch_callables() if not _app_ref: # running get_app for the first time # see docstring of `wait_for_workers_to_quit` for caveats on killing # workers at shutdown. app.aboutToQuit.connect(wait_for_workers_to_quit) # this will register all of our resources (icons) with Qt, so that they # can be used in qss files and elsewhere. _register_napari_resources() _app_ref = app # prevent garbage collection # Add the dispatcher attribute to the application to be able to dispatch # notifications coming from threads dispatcher = getattr(app, "_dispatcher", None) if dispatcher is None: app._dispatcher = NotificationDispatcher() return app
def cli( ctx: Context, hide_wm_frame: bool = True, aot: bool = True, theme: str = "Breeze", debug_disable_scrcpy: bool = False, ): """guiscrcpy: Graphical user interface for scrcpy""" print(fc("\n{b}guiscrcpy {v}{rst}", v=VERSION)) print(fc("by @srevinsaju")) print(fc("{x}https://github.com/srevinsaju/guiscrcpy{rst}\n\n")) if ctx.invoked_subcommand is not None: return try: # why this try block? # this is because, in case guiscrcpy crashes, # it will log the traceback to the terminal # but it would not be visible to users without CLI interface # enable High DPI scaling QApplication.setAttribute(QtCore.Qt.AA_EnableHighDpiScaling, True) # use HIGH DPI icons QApplication.setAttribute(QtCore.Qt.AA_UseHighDpiPixmaps, True) # init core app = QtWidgets.QApplication(sys.argv) config_manager = InterfaceConfig() bootstrap( app=app, config_manager=config_manager, theme=theme, aot=aot, hide_wm_frame=hide_wm_frame, debug_no_scrcpy=debug_disable_scrcpy, ) except ScrcpyNotFoundError: _msg_box = show_message_box( text="Scrcpy not found", info_text="guiscrcpy could not find scrcpy. " "Make sure you select scrcpy in the dialog box " "or add scrcpy to PATH. You can get the latest release " "of scrcpy from <a href='" "https://github.com/Genymobile/scrcpy'>" "Genymobile/scrcpy 's GitHub Releases</a> " "and select the <pre>scrcpy{ext}</pre> when you run " "guiscrcpy next time".format( ext=".exe" if platform.system() == "Windows" else "" ), ) _msg_box.exec_() print("Aborting!") sys.exit(-1) except AdbNotFoundError: _msg_box = show_message_box( text="ADB not found", info_text="guiscrcpy could not find adb. " "Make sure you select adb in the dialog box or add adb to PATH", ) _msg_box.exec_() print("Aborting!") sys.exit(-1) except InvalidConfigurationError: _msg_box = show_message_box( text="Invalid configuration error", info_text="The configuration file for guiscrcpy is invalid. <br>" "This is possibly because a new version of guiscrcpy " "was installed, or the old paths to `adb` and `scrcpy` " "as defined in the configuration file, no longer exists " "in the same path. To fix this error," "Run " "<pre>guiscrcpy config -r</pre> on your terminal.", ) _msg_box.exec_() print("Aborting!") sys.exit(-1) except ScrcpyServerNotFoundError: _msg_box = show_message_box( text="Scrcpy server not found error", info_text="The configuration file for guiscrcpy is invalid. <br>" "This is possibly because a new version of guiscrcpy " "was installed, or the old paths to `adb` and `scrcpy` " "as defined in the configuration file, no longer exists " "in the same path. To fix this error," "Run " "<pre>guiscrcpy config -r</pre> on your terminal.", ) _msg_box.exec_() print("Aborting!") sys.exit(-1) except Exception: # noqa: error_message = traceback.format_exc(chain=True) print(error_message) _msg_box = show_message_box( text="Error: Unhandled exception", info_text="<pre>{error_message}</pre>" "Please report this, if its a bug, to <a href=" "'https://github.com/srevinsaju/guiscrcpy/issues'>" "guiscrcpy bug tracker</a> as it will help to improve " "the next release.".format(error_message=error_message), ) _msg_box.exec_() print("Aborting!") sys.exit(-1)
def get_app( *, app_name: str = None, app_version: str = None, icon: str = None, org_name: str = None, org_domain: str = None, app_id: str = None, ) -> QApplication: """Get or create the Qt QApplication. There is only one global QApplication instance, which can be retrieved by calling get_app again, (or by using QApplication.instance()) Parameters ---------- app_name : str, optional Set app name (if creating for the first time), by default 'napari' app_version : str, optional Set app version (if creating for the first time), by default __version__ icon : str, optional Set app icon (if creating for the first time), by default NAPARI_ICON_PATH org_name : str, optional Set organization name (if creating for the first time), by default 'napari' org_domain : str, optional Set organization domain (if creating for the first time), by default 'napari.org' app_id : str, optional Set organization domain (if creating for the first time). Will be passed to set_app_id (which may also be called independently), by default NAPARI_APP_ID Returns ------- QApplication [description] Notes ----- Substitutes QApplicationWithTracing when the NAPARI_PERFMON env variable is set. If the QApplication already exists, we call convert_app_for_tracing() which deletes the QApplication and creates a new one. However here with get_app we need to create the correct QApplication up front, or we will crash because we'd be deleting the QApplication after we created QWidgets with it, such as we do for the splash screen. """ # napari defaults are all-or nothing. If any of the keywords are used # then they are all used. set_values = {k for k, v in locals().items() if v} kwargs = locals() if set_values else _defaults app = QApplication.instance() if app: if set_values: warn( "QApplication already existed, these arguments to to 'get_app'" " were ignored: {}".format(set_values)) if perf_config and perf_config.trace_qt_events: from .perf.qt_event_tracing import convert_app_for_tracing # no-op if app is already a QApplicationWithTracing app = convert_app_for_tracing(app) else: # automatically determine monitor DPI. # Note: this MUST be set before the QApplication is instantiated QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) if perf_config and perf_config.trace_qt_events: from .perf.qt_event_tracing import QApplicationWithTracing app = QApplicationWithTracing(sys.argv) else: app = QApplication(sys.argv) global _app_ref _app_ref = app # prevent garbage collection # if this is the first time the Qt app is being instantiated, we set # the name and metadata app.setApplicationName(kwargs.get('app_name')) app.setApplicationVersion(kwargs.get('app_version')) app.setOrganizationName(kwargs.get('org_name')) app.setOrganizationDomain(kwargs.get('org_domain')) app.setWindowIcon(QIcon(kwargs.get('icon'))) set_app_id(kwargs.get('app_id')) if perf_config and not perf_config.patched: # Will patch based on config file. perf_config.patch_callables() # see docstring of `wait_for_workers_to_quit` for caveats on killing # workers at shutdown. app.aboutToQuit.connect(wait_for_workers_to_quit) return app
from qtpyvcp.plugins import initialisePlugins, terminatePlugins, getPlugin from qtpyvcp.widgets.base_widgets.base_widget import VCPPrimitiveWidget from qtpyvcp.widgets.form_widgets.main_window import VCPMainWindow # initialize logging. If a base logger was already initialized in a startup # script (e.g. vcp_launcher.py), then that logger will be returned, otherwise # this will initialise a base logger with default log level of DEBUG LOG = initBaseLogger('qtpyvcp') # Needed to silence this PySide2 warning: # Qt WebEngine seems to be initialized from a plugin. Please set # Qt::AA_ShareOpenGLContexts using QCoreApplication::setAttribute # before constructing QGuiApplication. if API == 'pyside2': from qtpy.QtCore import Qt QApplication.setAttribute(Qt.AA_ShareOpenGLContexts) class VCPApplication(QApplication): def __init__(self, theme=None, stylesheet=None, custom_fonts=[]): app_args = (qtpyvcp.OPTIONS.command_line_args or "").split() super(VCPApplication, self).__init__(app_args) opts = qtpyvcp.OPTIONS self.status = getPlugin('status') # initialize plugins initialisePlugins() theme = opts.theme or theme
import argparse import pathlib import sys from qtpy.QtCore import Qt from qtpy.QtWidgets import QApplication # from qtconsole.inprocess import QtInProcessKernelManager QApplication.setAttribute(Qt.AA_EnableHighDpiScaling, True) # Back up the reference to the exceptionhook sys._excepthook = sys.excepthook def exception_hook(exctype, value, traceback): """Catch qtpy exceptions.""" # https://stackoverflow.com/questions/43039048/pyqt5-fails-with-cryptic-message # Print the error and traceback print(exctype, value, traceback) # Call the normal Exception hook after sys._excepthook(exctype, value, traceback) sys.exit(1) def process_cl_args(): """Process known arguments.""" parser = argparse.ArgumentParser(description='Directly open isotherms.') parser.add_argument( '--file', '-f',
def _main(args): # To avoid problems when testing without screen if args.test or args.screenshots: os.environ['QT_QPA_PLATFORM'] = 'offscreen' # Set QT_API variable before importing QtPy if args.qt_from in ['pyqt', 'pyqt5', 'pyside', 'pyside2']: os.environ['QT_API'] = args.qt_from elif args.qt_from == 'pyqtgraph': os.environ['QT_API'] = os.environ['PYQTGRAPH_QT_LIB'] elif args.qt_from in ['qt.py', 'qt']: try: import Qt except ImportError: print('Could not import Qt (Qt.Py)') else: os.environ['QT_API'] = Qt.__binding__ # QtPy imports from qtpy import API_NAME, QT_VERSION, PYQT_VERSION, PYSIDE_VERSION from qtpy import __version__ as QTPY_VERSION from qtpy.QtWidgets import (QApplication, QMainWindow, QDockWidget, QStatusBar, QLabel, QMenu) from qtpy.QtCore import QTimer, Qt, QSettings # Set API_VERSION variable API_VERSION = '' if PYQT_VERSION: API_VERSION = PYQT_VERSION elif PYSIDE_VERSION: API_VERSION = PYSIDE_VERSION else: API_VERSION = 'Not found' # Import examples UI from mw_menus_ui import Ui_MainWindow as ui_main from dw_buttons_ui import Ui_DockWidget as ui_buttons from dw_displays_ui import Ui_DockWidget as ui_displays from dw_inputs_fields_ui import Ui_DockWidget as ui_inputs_fields from dw_inputs_no_fields_ui import Ui_DockWidget as ui_inputs_no_fields from dw_widgets_ui import Ui_DockWidget as ui_widgets from dw_views_ui import Ui_DockWidget as ui_views from dw_containers_tabs_ui import Ui_DockWidget as ui_containers_tabs from dw_containers_no_tabs_ui import Ui_DockWidget as ui_containers_no_tabs # qrainbowstyle.useDarwinButtons() QApplication.setAttribute(Qt.AA_UseHighDpiPixmaps) QApplication.setAttribute(Qt.AA_EnableHighDpiScaling) # create the application if not QApplication.instance(): app = QApplication(sys.argv) else: app = QApplication.instance() app.setOrganizationName('QRainbowStyle') app.setApplicationName('QRainbowStyle Example') styles = qrainbowstyle.getAvailableStyles() style = args.style if not args.style: style = styles[random.randint(0, len(styles)) - 1] app.setStyleSheet(qrainbowstyle.load_stylesheet(style=str(style))) # create main window window = qrainbowstyle.windows.FramelessWindow() window.setTitlebarHeight(30) widget = QMainWindow(window) widget.setWindowFlags(Qt.Widget) widget.setObjectName('mainwindow') ui = ui_main() ui.setupUi(widget) window.addContentWidget(widget) title = ("QRainbowStyle Example - " + "(QRainbowStyle=v" + qrainbowstyle.__version__ + ", QtPy=v" + QTPY_VERSION + ", " + API_NAME + "=v" + API_VERSION + ", Qt=v" + QT_VERSION + ", Python=v" + platform.python_version() + ")") _logger.info(title) window.setWindowTitle(title) # Create docks for buttons dw_buttons = QDockWidget() dw_buttons.setObjectName('buttons') ui_buttons = ui_buttons() ui_buttons.setupUi(dw_buttons) widget.addDockWidget(Qt.RightDockWidgetArea, dw_buttons) # Add actions on popup toolbuttons menu = QMenu() for action in ['Action A', 'Action B', 'Action C']: menu.addAction(action) ui_buttons.toolButtonDelayedPopup.setMenu(menu) ui_buttons.toolButtonInstantPopup.setMenu(menu) ui_buttons.toolButtonMenuButtonPopup.setMenu(menu) # Create docks for buttons dw_displays = QDockWidget() dw_displays.setObjectName('displays') ui_displays = ui_displays() ui_displays.setupUi(dw_displays) widget.addDockWidget(Qt.RightDockWidgetArea, dw_displays) # Create docks for inputs - no fields dw_inputs_no_fields = QDockWidget() dw_inputs_no_fields.setObjectName('inputs_no_fields') ui_inputs_no_fields = ui_inputs_no_fields() ui_inputs_no_fields.setupUi(dw_inputs_no_fields) widget.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_no_fields) # Create docks for inputs - fields dw_inputs_fields = QDockWidget() dw_inputs_fields.setObjectName('inputs_fields') ui_inputs_fields = ui_inputs_fields() ui_inputs_fields.setupUi(dw_inputs_fields) widget.addDockWidget(Qt.RightDockWidgetArea, dw_inputs_fields) # Create docks for widgets dw_widgets = QDockWidget() dw_widgets.setObjectName('widgets') ui_widgets = ui_widgets() ui_widgets.setupUi(dw_widgets) widget.addDockWidget(Qt.LeftDockWidgetArea, dw_widgets) # Create docks for views dw_views = QDockWidget() dw_views.setObjectName('views') ui_views = ui_views() ui_views.setupUi(dw_views) widget.addDockWidget(Qt.LeftDockWidgetArea, dw_views) # Create docks for containers - no tabs dw_containers_no_tabs = QDockWidget() dw_containers_no_tabs.setObjectName('containers_no_tabs') ui_containers_no_tabs = ui_containers_no_tabs() ui_containers_no_tabs.setupUi(dw_containers_no_tabs) widget.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_no_tabs) # Create docks for containters - tabs dw_containers_tabs = QDockWidget() dw_containers_tabs.setObjectName('containers_tabs') ui_containers_tabs = ui_containers_tabs() ui_containers_tabs.setupUi(dw_containers_tabs) widget.addDockWidget(Qt.LeftDockWidgetArea, dw_containers_tabs) # Tabify right docks widget.tabifyDockWidget(dw_buttons, dw_displays) widget.tabifyDockWidget(dw_displays, dw_inputs_fields) widget.tabifyDockWidget(dw_inputs_fields, dw_inputs_no_fields) # Tabify left docks widget.tabifyDockWidget(dw_containers_no_tabs, dw_containers_tabs) widget.tabifyDockWidget(dw_containers_tabs, dw_widgets) widget.tabifyDockWidget(dw_widgets, dw_views) # Issues #9120, #9121 on Spyder qstatusbar = QStatusBar() qstatusbar.addWidget(QLabel('Style')) qstatusbarbutton = qrainbowstyle.widgets.StylePickerHorizontal() qstatusbar.addWidget(qstatusbarbutton) qstatusbar.setSizeGripEnabled(False) # Add info also in status bar for screenshots get it qstatusbar.addWidget(QLabel('INFO: ' + title)) widget.setStatusBar(qstatusbar) # Todo: add report info and other info in HELP graphical # Auto quit after 2s when in test mode if args.test: QTimer.singleShot(2000, app.exit) _read_settings(widget, args.reset, QSettings) window.show() # window.showMaximized() app.exec_() _write_settings(widget, QSettings)