Python qtpy.QtWidgets.QApplication.instance() Examples

The following are 23 code examples of qtpy.QtWidgets.QApplication.instance(). You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may also want to check out all available functions/classes of the module qtpy.QtWidgets.QApplication , or try the search function .
Example #1
Source File: clipboards.py    From recruit with Apache License 2.0 6 votes vote down vote up
def init_qt_clipboard():
    # $DISPLAY should exist

    # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
    try:
        from qtpy.QtWidgets import QApplication
    except ImportError:
        try:
            from PyQt5.QtWidgets import QApplication
        except ImportError:
            from PyQt4.QtGui import QApplication

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    def copy_qt(text):
        cb = app.clipboard()
        cb.setText(text)

    def paste_qt():
        cb = app.clipboard()
        return text_type(cb.text())

    return copy_qt, paste_qt 
Example #2
Source File: clipboards.py    From vnpy_crypto with MIT License 6 votes vote down vote up
def init_qt_clipboard():
    # $DISPLAY should exist

    # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
    try:
        from qtpy.QtWidgets import QApplication
    except ImportError:
        try:
            from PyQt5.QtWidgets import QApplication
        except ImportError:
            from PyQt4.QtGui import QApplication

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    def copy_qt(text):
        cb = app.clipboard()
        cb.setText(text)

    def paste_qt():
        cb = app.clipboard()
        return text_type(cb.text())

    return copy_qt, paste_qt 
Example #3
Source File: clipboards.py    From predictive-maintenance-using-machine-learning with Apache License 2.0 6 votes vote down vote up
def init_qt_clipboard():
    # $DISPLAY should exist

    # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
    try:
        from qtpy.QtWidgets import QApplication
    except ImportError:
        try:
            from PyQt5.QtWidgets import QApplication
        except ImportError:
            from PyQt4.QtGui import QApplication

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    def copy_qt(text):
        cb = app.clipboard()
        cb.setText(text)

    def paste_qt():
        cb = app.clipboard()
        return text_type(cb.text())

    return copy_qt, paste_qt 
Example #4
Source File: qthelpers.py    From conda-manager with MIT License 6 votes vote down vote up
def qapplication(translate=True, test_time=3):
    """Return QApplication instance
    Creates it if it doesn't already exist"""
    app = QApplication.instance()
    if app is None:
        app = QApplication(['Conda-Manager'])
        app.setApplicationName('Conda-Manager')
    if translate:
        install_translator(app)

    test_travis = os.environ.get('TEST_CI', None)
    if test_travis is not None:
        timer_shutdown = QTimer(app)
        timer_shutdown.timeout.connect(app.quit)
        timer_shutdown.start(test_time*1000)
    return app 
Example #5
Source File: qthelpers.py    From conda-manager with MIT License 5 votes vote down vote up
def install_translator(qapp):
    """Install Qt translator to the QApplication instance"""
    global QT_TRANSLATOR
    if QT_TRANSLATOR is None:
        qt_translator = QTranslator()
        if qt_translator.load(
           "qt_"+QLocale.system().name(),
           QLibraryInfo.location(QLibraryInfo.TranslationsPath)):
            QT_TRANSLATOR = qt_translator  # Keep reference alive
    if QT_TRANSLATOR is not None:
        qapp.installTranslator(QT_TRANSLATOR) 
Example #6
Source File: __init__.py    From gist-alfred with MIT License 5 votes vote down vote up
def init_qt_clipboard():
    global QApplication
    # $DISPLAY should exist

    # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
    try:
        from qtpy.QtWidgets import QApplication
    except:
        try:
            from PyQt5.QtWidgets import QApplication
        except:
            from PyQt4.QtGui import QApplication

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    def copy_qt(text):
        text = _stringifyText(text) # Converts non-str values to str.
        cb = app.clipboard()
        cb.setText(text)

    def paste_qt():
        cb = app.clipboard()
        return STR_OR_UNICODE(cb.text())

    return copy_qt, paste_qt 
Example #7
Source File: test_patch_qheaderview.py    From qtpy with MIT License 5 votes vote down vote up
def get_qapp(icon_path=None):
    qapp = QApplication.instance()
    if qapp is None:
        qapp = QApplication([''])
    return qapp 
Example #8
Source File: Pyperclip.py    From MIA-Dictionary-Addon with GNU General Public License v3.0 5 votes vote down vote up
def init_qt_clipboard():
    global QApplication
    # $DISPLAY should exist

    # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
    try:
        from qtpy.QtWidgets import QApplication
    except:
        try:
            from PyQt5.QtWidgets import QApplication
        except:
            from PyQt4.QtGui import QApplication

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    def copy_qt(text):
        text = _stringifyText(text) # Converts non-str values to str.
        cb = app.clipboard()
        cb.setText(text)

    def paste_qt():
        cb = app.clipboard()
        return STR_OR_UNICODE(cb.text())

    return copy_qt, paste_qt 
Example #9
Source File: Pyperclip.py    From MIA-Japanese-Add-on with GNU General Public License v3.0 5 votes vote down vote up
def init_qt_clipboard():
    global QApplication
    # $DISPLAY should exist

    # Try to import from qtpy, but if that fails try PyQt5 then PyQt4
    try:
        from qtpy.QtWidgets import QApplication
    except:
        try:
            from PyQt5.QtWidgets import QApplication
        except:
            from PyQt4.QtGui import QApplication

    app = QApplication.instance()
    if app is None:
        app = QApplication([])

    def copy_qt(text):
        text = _stringifyText(text) # Converts non-str values to str.
        cb = app.clipboard()
        cb.setText(text)

    def paste_qt():
        cb = app.clipboard()
        return STR_OR_UNICODE(cb.text())

    return copy_qt, paste_qt 
Example #10
Source File: iconic_font.py    From qtawesome with MIT License 5 votes vote down vote up
def icon(self, *names, **kwargs):
        """Return a QIcon object corresponding to the provided icon name."""
        cache_key = '{}{}'.format(names,kwargs)
        if cache_key not in self.icon_cache:
            options_list = kwargs.pop('options', [{}] * len(names))
            general_options = kwargs

            if len(options_list) != len(names):
                error = '"options" must be a list of size {0}'.format(len(names))
                raise Exception(error)

            if QApplication.instance() is not None:
                parsed_options = []
                for i in range(len(options_list)):
                    specific_options = options_list[i]
                    parsed_options.append(self._parse_options(specific_options,
                                                              general_options,
                                                              names[i]))

                # Process high level API
                api_options = parsed_options

                self.icon_cache[cache_key] = self._icon_by_painter(self.painter, api_options)
            else:
                warnings.warn("You need to have a running "
                              "QApplication to use QtAwesome!")
                return QIcon()
        return self.icon_cache[cache_key] 
Example #11
Source File: test_patch_qheaderview.py    From P4VFX with MIT License 5 votes vote down vote up
def get_qapp(icon_path=None):
    qapp = QApplication.instance()
    if qapp is None:
        qapp = QApplication([''])
    return qapp 
Example #12
Source File: test_patch_qheaderview.py    From P4VFX with MIT License 5 votes vote down vote up
def get_qapp(icon_path=None):
    qapp = QApplication.instance()
    if qapp is None:
        qapp = QApplication([''])
    return qapp 
Example #13
Source File: test_patch_qheaderview.py    From winpython with MIT License 5 votes vote down vote up
def get_qapp(icon_path=None):
    qapp = QApplication.instance()
    if qapp is None:
        qapp = QApplication([''])
    return qapp 
Example #14
Source File: mainwindow.py    From qtmodern with MIT License 5 votes vote down vote up
def darkTheme(self):
        qtmodern.styles.dark(QApplication.instance()) 
Example #15
Source File: mainwindow.py    From qtmodern with MIT License 5 votes vote down vote up
def lightTheme(self):
        qtmodern.styles.light(QApplication.instance()) 
Example #16
Source File: benchmark_qt_viewer_labels.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self):
        _ = QApplication.instance() or QApplication([])
        np.random.seed(0)
        self.data = np.random.randint(10, size=(512, 512))
        self.viewer = napari.view_labels(self.data)
        self.layer = self.viewer.layers[0]
        self.layer.brush_size = 10
        self.layer.mode = 'paint'
        self.layer.selected_label = 3
        self.layer._last_cursor_coord = (511, 511)
        Event = collections.namedtuple('Event', 'is_dragging')
        self.event = Event(is_dragging=True) 
Example #17
Source File: benchmark_qt_viewer_image.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self):
        _ = QApplication.instance() or QApplication([])
        np.random.seed(0)
        self.data = np.random.random((128, 128, 128))
        self.new_data = np.random.random((128, 128, 128))
        self.viewer = napari.view_image(self.data) 
Example #18
Source File: benchmark_qt_viewer_image.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self, n):
        _ = QApplication.instance() or QApplication([])
        np.random.seed(0)
        self.data = np.random.random((n, n))
        self.viewer = napari.view_image(self.data) 
Example #19
Source File: benchmark_qt_viewer_image.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self, n):
        _ = QApplication.instance() or QApplication([])
        np.random.seed(0)
        self.data = np.random.random((n, n))
        self.viewer = napari.Viewer() 
Example #20
Source File: benchmark_qt_viewer_image.py    From napari with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def setup(self, n):
        _ = QApplication.instance() or QApplication([])
        np.random.seed(0)
        self.data = np.random.random((n, n))
        self.viewer = None 
Example #21
Source File: test_patch_qheaderview.py    From vnpy_crypto with MIT License 5 votes vote down vote up
def get_qapp(icon_path=None):
    qapp = QApplication.instance()
    if qapp is None:
        qapp = QApplication([''])
    return qapp 
Example #22
Source File: viewer.py    From napari with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def __init__(
        self,
        title='napari',
        ndisplay=2,
        order=None,
        axis_labels=None,
        show=True,
    ):
        # instance() returns the singleton instance if it exists, or None
        app = QApplication.instance()
        # if None, raise a RuntimeError with the appropriate message
        if app is None:
            message = (
                "napari requires a Qt event loop to run. To create one, "
                "try one of the following: \n"
                "  - use the `napari.gui_qt()` context manager. See "
                "https://github.com/napari/napari/tree/master/examples for"
                " usage examples.\n"
                "  - In IPython or a local Jupyter instance, use the "
                "`%gui qt` magic command.\n"
                "  - Launch IPython with the option `--gui=qt`.\n"
                "  - (recommended) in your IPython configuration file, add"
                " or uncomment the line `c.TerminalIPythonApp.gui = 'qt'`."
                " Then, restart IPython."
            )
            raise RuntimeError(message)

        # For perfmon we need a special QApplication. If using gui_qt we already
        # have the special one, and this is a noop. When running inside IPython
        # or Jupyter however this is where we switch out the QApplication.
        if os.getenv("NAPARI_PERFMON", "0") != "0":
            from ._qt.qt_event_timing import convert_app_for_timing

            app = convert_app_for_timing(app)

        if (
            platform.system() == "Windows"
            and not getattr(sys, 'frozen', False)
            and self._napari_app_id
        ):
            import ctypes

            ctypes.windll.shell32.SetCurrentProcessExplicitAppUserModelID(
                self._napari_app_id
            )

        logopath = join(dirname(__file__), 'resources', 'logo.png')
        app.setWindowIcon(QIcon(logopath))

        # see docstring of `wait_for_workers_to_quit` for caveats on killing
        # workers at shutdown.
        app.aboutToQuit.connect(wait_for_workers_to_quit)

        super().__init__(
            title=title,
            ndisplay=ndisplay,
            order=order,
            axis_labels=axis_labels,
        )
        qt_viewer = QtViewer(self)
        self.window = Window(qt_viewer, show=show) 
Example #23
Source File: event_loop.py    From napari with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
def gui_qt(*, startup_logo=False):
    """Start a Qt event loop in which to run the application.

    Parameters
    ----------
    startup_logo : bool
        Show a splash screen with the napari logo during startup.

    Notes
    -----
    This context manager is not needed if running napari within an interactive
    IPython session. In this case, use the ``%gui qt`` magic command, or start
    IPython with the Qt GUI event loop enabled by default by using
    ``ipython --gui=qt``.
    """
    splash_widget = None
    app = QApplication.instance()
    if not app:
        # automatically determine monitor DPI.
        # Note: this MUST be set before the QApplication is instantiated
        QApplication.setAttribute(Qt.AA_EnableHighDpiScaling)
        # if this is the first time the Qt app is being instantiated, we set
        # the name, so that we know whether to raise_ in Window.show()
        app = _create_application(sys.argv)
        app.setApplicationName('napari')
        if startup_logo:
            logopath = join(dirname(__file__), '..', 'resources', 'logo.png')
            pm = QPixmap(logopath).scaled(
                360, 360, Qt.KeepAspectRatio, Qt.SmoothTransformation
            )
            splash_widget = QSplashScreen(pm)
            splash_widget.show()
            app._splash_widget = splash_widget
    else:
        app._existed = True
    yield app
    # if the application already existed before this function was called,
    # there's no need to start it again.  By avoiding unnecessary calls to
    # ``app.exec_``, we avoid blocking.
    if app.applicationName() == 'napari':
        if splash_widget and startup_logo:
            splash_widget.close()
        app.exec_()