Python PyQt5.QtWidgets.QApplication.instance() Examples

The following are 30 code examples of PyQt5.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 PyQt5.QtWidgets.QApplication , or try the search function .
Example #1
Source File: engine.py    From autokey with GNU General Public License v3.0 7 votes vote down vote up
def __init__(self, parent: QWidget=None):
        super(EngineSettings, self).__init__(parent)
        self.setupUi(self)

        # Save the path label text stored in the Qt UI file.
        # It is used to reset the label to this value if a custom module path is currently set and the user deletes it.
        # Do not hard-code it to prevent possible inconsistencies.
        self.initial_folder_label_text = self.folder_label.text()

        self.config_manager = QApplication.instance().configManager
        self.path = self.config_manager.userCodeDir
        self.clear_button.setEnabled(self.path is not None)

        if self.config_manager.userCodeDir is not None:
            self.folder_label.setText(self.config_manager.userCodeDir)
        logger.debug("EngineSettings widget initialised, custom module search path is set to: {}".format(self.path)) 
Example #2
Source File: console.py    From CQ-editor with Apache License 2.0 6 votes vote down vote up
def __init__(self, customBanner=None, namespace=dict(), *args, **kwargs):
        super(ConsoleWidget, self).__init__(*args, **kwargs)

#        if not customBanner is None:
#            self.banner = customBanner

        self.font_size = 6
        self.kernel_manager = kernel_manager = QtInProcessKernelManager()
        kernel_manager.start_kernel(show_banner=False)
        kernel_manager.kernel.gui = 'qt'
        kernel_manager.kernel.shell.banner1 = ""
        
        self.kernel_client = kernel_client = self._kernel_manager.client()
        kernel_client.start_channels()

        def stop():
            kernel_client.stop_channels()
            kernel_manager.shutdown_kernel()
            QApplication.instance().exit()

        self.exit_requested.connect(stop)
        
        self.clear()
        
        self.push_vars(namespace) 
Example #3
Source File: test_readlinecommands.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def _validate_deletion(lineedit, method, text, deleted, rest):
    """Run and validate a text deletion method on the ReadLine bridge.

    Args:
        lineedit: The LineEdit instance.
        method: Reference to the method on the bridge to test.
        text: The starting 'augmented' text (see LineEdit.set_aug_text)
        deleted: The text that should be deleted when the method is invoked.
        rest: The augmented text that should remain after method is invoked.
    """
    lineedit.set_aug_text(text)
    method()
    assert readlinecommands.bridge._deleted[lineedit] == deleted
    assert lineedit.aug_text() == rest
    lineedit.clear()
    readlinecommands.rl_yank()
    assert lineedit.aug_text() == deleted + '|' 
Example #4
Source File: utils.py    From Dwarf with GNU General Public License v3.0 6 votes vote down vote up
def set_theme(theme, prefs=None):
    if theme:
        theme = theme.replace(os.pardir, '').replace('.', '')
        theme = theme.join(theme.split()).lower()
        theme_style = resource_path('assets' + os.sep + theme + '_style.qss')
        if not os.path.exists(theme_style):
            theme_style = ':/assets/' + theme + '_style.qss'

        if prefs is not None:
            prefs.put('dwarf_ui_theme', theme)

        try:
            _app = QApplication.instance()
            style_s = QFile(theme_style)
            style_s.open(QFile.ReadOnly)
            style_content = QTextStream(style_s).readAll()
            _app.setStyleSheet(_app.styleSheet() + '\n' + style_content)
        except Exception as e:
            pass
            # err = self.dwarf.spawn(dwarf_args.package, dwarf_args.script) 
Example #5
Source File: quitter.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def quit_(save: bool = False,
          session: sessions.ArgType = None) -> None:
    """Quit qutebrowser.

    Args:
        save: When given, save the open windows even if auto_save.session
                is turned off.
        session: The name of the session to save.
    """
    if session is not None and not save:
        raise cmdutils.CommandError("Session name given without --save!")
    if save:
        if session is None:
            session = sessions.default
        instance.shutdown(session=session)
    else:
        instance.shutdown() 
Example #6
Source File: loading_dialog.py    From CvStudio with MIT License 6 votes vote down vote up
def __init__(self, parent=None):
        super(QLoadingDialog, self).__init__()
        self.setFixedSize(100, 100)
        # self.setWindowOpacity(0.8)
        self.setWindowFlags(QtCore.Qt.FramelessWindowHint)
        self.setAttribute(QtCore.Qt.WA_TranslucentBackground)
        app = QApplication.instance()
        curr_theme = "light"
        if app:
            curr_theme = app.property("theme")
        gif_file = os.path.abspath("./assets/icons/{}/loading.gif".format(curr_theme))
        self.movie = QMovie(gif_file)
        self.label = QLabel()
        self.label.setMovie(self.movie)
        self.layout = QVBoxLayout(self)
        self.layout.addWidget(self.label) 
Example #7
Source File: utilcmds.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def later(ms: int, command: str, win_id: int) -> None:
    """Execute a command after some time.

    Args:
        ms: How many milliseconds to wait.
        command: The command to run, with optional args.
    """
    if ms < 0:
        raise cmdutils.CommandError("I can't run something in the past!")
    commandrunner = runners.CommandRunner(win_id)
    timer = usertypes.Timer(name='later', parent=QApplication.instance())
    try:
        timer.setSingleShot(True)
        try:
            timer.setInterval(ms)
        except OverflowError:
            raise cmdutils.CommandError("Numeric argument is too large for "
                                        "internal int representation.")
        timer.timeout.connect(
            functools.partial(commandrunner.run_safely, command))
        timer.timeout.connect(timer.deleteLater)
        timer.start()
    except:
        timer.deleteLater()
        raise 
Example #8
Source File: eventfilter.py    From qutebrowser with GNU General Public License v3.0 6 votes vote down vote up
def _handle_key_event(self, event: QKeyEvent) -> bool:
        """Handle a key press/release event.

        Args:
            event: The QEvent which is about to be delivered.

        Return:
            True if the event should be filtered, False if it's passed through.
        """
        active_window = QApplication.instance().activeWindow()
        if active_window not in objreg.window_registry.values():
            # Some other window (print dialog, etc.) is focused so we pass the
            # event through.
            return False
        try:
            man = modeman.instance('current')
            return man.handle_event(event)
        except objreg.RegistryUnavailableError:
            # No window available yet, or not a MainWindow
            return False 
Example #9
Source File: theme.py    From FeelUOwn with GNU General Public License v3.0 6 votes vote down vote up
def load_macos_dark(self):
        """
        So many DEs on Linux! Hard to compat! We give them macOS
        dark theme colors!

        Users can also design a theme colors by themselves,
        we provider dump_colors/load_colors function for conviniece.
        """
        self.load_dark()
        content = read_resource('macos_dark.colors')
        colors = json.loads(content)
        try:
            QApplication.instance().paletteChanged.disconnect(self.autoload)
        except TypeError:
            pass
        palette = load_colors(colors)
        self._app.setPalette(palette)
        QApplication.instance().paletteChanged.connect(self.autoload) 
Example #10
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 #11
Source File: schedule_tab.py    From vorta with GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent=None):
        super().__init__(parent)
        self.setupUi(parent)
        self.app = QApplication.instance()
        self.toolBox.setCurrentIndex(0)

        self.schedulerRadioMapping = {
            'off': self.scheduleOffRadio,
            'interval': self.scheduleIntervalRadio,
            'fixed': self.scheduleFixedRadio
        }

        self.scheduleApplyButton.clicked.connect(self.on_scheduler_apply)
        self.app.backup_finished_event.connect(self.init_logs)

        self.init_logs()
        self.populate_from_profile()
        self.set_icons() 
Example #12
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 #13
Source File: base.py    From BrainSpace with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def _get_qt_app():
    app = None

    if in_ipython():
        from IPython import get_ipython
        ipython = get_ipython()
        ipython.magic('gui qt')

        from IPython.external.qt_for_kernel import QtGui
        app = QtGui.QApplication.instance()

    if app is None:
        from PyQt5.QtWidgets import QApplication
        app = QApplication.instance()
        if not app:
            app = QApplication([''])

    return app 
Example #14
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 #15
Source File: main.py    From PyQt5-Apps with GNU General Public License v3.0 6 votes vote down vote up
def changeLanguage(self, lan):
        """:author : Tich
        :param lan: 0=>Chinese, 1=>English
        change ui language
        """
        if lan == 0 and self.lan != 0:
            self.lan = 0
            print("[MainWindow] Change to zh_CN")
            self.trans.load("zh_CN")
        elif lan == 1 and self.lan != 1:
            self.lan = 1
            print("[MainWindow] Change to English")
            self.trans.load("en")
        else:
            return
        _app = QApplication.instance()
        _app.installTranslator(self.trans)
        self.retranslateUi(self) 
Example #16
Source File: theme.py    From FeelUOwn with GNU General Public License v3.0 5 votes vote down vote up
def load_dark(self):
        common = read_resource('common.qss')
        dark = read_resource('dark.qss')
        QApplication.instance().setStyleSheet(common + dark) 
Example #17
Source File: theme.py    From FeelUOwn with GNU General Public License v3.0 5 votes vote down vote up
def load_light(self):
        common = read_resource('common.qss')
        light = read_resource('light.qss')
        QApplication.instance().setStyleSheet(common + light) 
Example #18
Source File: theme.py    From FeelUOwn with GNU General Public License v3.0 5 votes vote down vote up
def initialize(self):
        # XXX: I don't know why we should autoload twice
        # to make it work well on Linux(GNOME)
        self.autoload()
        self._app.initialized.connect(lambda app: self.autoload(), weak=False)
        QApplication.instance().paletteChanged.connect(lambda p: self.autoload()) 
Example #19
Source File: utils.py    From vorta with GNU General Public License v3.0 5 votes vote down vote up
def is_system_tray_available():
    app = QApplication.instance()
    if app is None:
        app = QApplication([])
        tray = QSystemTrayIcon()
        is_available = tray.isSystemTrayAvailable()
        app.quit()
    else:
        tray = QSystemTrayIcon()
        is_available = tray.isSystemTrayAvailable()

    return is_available 
Example #20
Source File: utils.py    From vorta with GNU General Public License v3.0 5 votes vote down vote up
def uses_dark_mode():
    """
    This function detects if we are running in dark mode (e.g. macOS dark mode).
    """
    palette = QApplication.instance().palette()
    return palette.windowText().color().lightness() > palette.window().color().lightness() 
Example #21
Source File: Utils.py    From Jade-Application-Kit with GNU General Public License v3.0 5 votes vote down vote up
def record(name: str, _type: object) -> None:
        """
        * :Usage: Instance.record("name", object)
        * Should only be used once per instance
        """
        register[name] = _type
        print(f"Registering ['{name}'] Instance") 
Example #22
Source File: configwindow.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def _connect_all_settings_menu_signals(self):
        # TODO: Connect and implement unconnected actions
        app = QApplication.instance()
        # Sync the action_enable_monitoring checkbox with the global state. Prevents a desync when the global hotkey
        # is used
        app.monitoring_disabled.connect(self.action_enable_monitoring.setChecked)

        self.action_enable_monitoring.triggered.connect(app.toggle_service)
        self.action_show_log_view.triggered.connect(self.on_show_log)

        self.action_configure_shortcuts.triggered.connect(self._none_action)  # Currently not shown in any menu
        self.action_configure_toolbars.triggered.connect(self._none_action)  # Currently not shown in any menu
        # Both actions above were part of the KXMLGUI window functionality and allowed to customize keyboard shortcuts
        # and toolbar items
        self.action_configure_autokey.triggered.connect(self.on_advanced_settings) 
Example #23
Source File: settingsdialog.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def accept(self):
        logger.info("User requested to save the settings.")
        app = QApplication.instance()  # type: Application
        self.general_settings_page.save()
        self.special_hotkeys_page.save()
        self.script_engine_page.save()
        app.configManager.config_altered(True)
        app.update_notifier_visibility()
        app.notifier.reset_tray_icon()
        super(SettingsDialog, self).accept()
        logger.debug("Save completed, dialog window hidden.") 
Example #24
Source File: specialhotkeys.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QWidget=None):
        super(SpecialHotkeySettings, self).__init__(parent)
        self.setupUi(self)


        self.show_config_dlg = GlobalHotkeyDialog(parent)
        self.toggle_monitor_dlg = GlobalHotkeyDialog(parent)
        self.use_config_hotkey = False
        self.use_service_hotkey = False
        app = QApplication.instance()  # type: Application
        self.config_manager = app.configManager
        self.use_config_hotkey = self._load_hotkey(self.config_manager.configHotkey, self.config_key_label,
                                                   self.show_config_dlg, self.clear_config_button)
        self.use_service_hotkey = self._load_hotkey(self.config_manager.toggleServiceHotkey, self.monitor_key_label,
                                                    self.toggle_monitor_dlg, self.clear_monitor_button) 
Example #25
Source File: signal.py    From linux-show-player with GNU General Public License v3.0 5 votes vote down vote up
def call(self, *args, **kwargs):
        QApplication.instance().postEvent(self._invoker,
                                          self._event(*args, **kwargs)) 
Example #26
Source File: signal.py    From linux-show-player with GNU General Public License v3.0 5 votes vote down vote up
def call(self, *args, **kwargs):
        QApplication.instance().sendEvent(self._invoker,
                                          self._event(*args, **kwargs)) 
Example #27
Source File: signal.py    From linux-show-player with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

        # Create a QObject and move it to mainloop thread
        self._invoker = QObject()
        self._invoker.moveToThread(QApplication.instance().thread())
        self._invoker.customEvent = self._custom_event 
Example #28
Source File: load_visuals_txt.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, text):
            if QApplication.instance() is None:
                self.dialog = None
                print(text)
            else:
                self.dialog = QProgressDialog(text, 'Cancel', 0, 100)
                self.dialog.setWindowFlags(Qt.WindowStaysOnTopHint)
                self.dialog.show() 
Example #29
Source File: mainwindow.py    From bluesky with GNU General Public License v3.0 5 votes vote down vote up
def closeEvent(self, event=None):
        # Send quit to server if we own the host
        if self.mode != 'client':
            bs.net.send_event(b'QUIT')
        app.instance().closeAllWindows()
        # return True 
Example #30
Source File: qtapp.py    From autokey with GNU General Public License v3.0 5 votes vote down vote up
def postEventWithCallback(self, callback, *args):
        self.queue.put((callback, args))
        app = QApplication.instance()
        app.postEvent(self, QEvent(QEvent.User))