Python PyQt5.QtCore.QCoreApplication.instance() Examples

The following are 19 code examples of PyQt5.QtCore.QCoreApplication.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.QtCore.QCoreApplication , or try the search function .
Example #1
Source File: error.py    From malss with MIT License 7 votes vote down vote up
def __init__(self, parent=None, button_func=None, params=None):
        super().__init__(parent, 'Error', params)

        if self.params.lang == 'en':
            text = ('Unexpected error occured.\n'
                    'Please exit the application and solve the problem.')
        else:
            text = ('予期せぬエラーが発生しました。\n'
                    'アプリケーションを終了し,問題を解決してください。')
        self.set_paragraph('Unexpected error', text=text)

        self.set_paragraph('Traceback log', text=self.params.error)

        self.vbox.addStretch(1)

        btn = QPushButton('Exit', self.inner)
        btn.setStyleSheet('QPushButton{font: bold; font-size: 15pt; background-color: white;};')
        btn.clicked.connect(QCoreApplication.instance().quit)

        self.vbox.addWidget(btn) 
Example #2
Source File: welcome.py    From gridsync with GNU General Public License v3.0 6 votes vote down vote up
def closeEvent(self, event):
        if self.gui.main_window.gateways:
            event.accept()
        else:
            event.ignore()
            msgbox = QMessageBox(self)
            msgbox.setIcon(QMessageBox.Question)
            msgbox.setWindowTitle("Exit setup?")
            msgbox.setText("Are you sure you wish to exit?")
            msgbox.setInformativeText(
                "{} has not yet been configured.".format(APP_NAME)
            )
            msgbox.setStandardButtons(QMessageBox.Yes | QMessageBox.No)
            msgbox.setDefaultButton(QMessageBox.No)
            if msgbox.exec_() == QMessageBox.Yes:
                if sys.platform == "win32":
                    self.gui.systray.hide()
                QCoreApplication.instance().quit() 
Example #3
Source File: Theme.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getInstance(cls, engine = None) -> "Theme":
        """Get the singleton instance for this class."""

        # Note: Explicit use of class name to prevent issues with inheritance.
        if Theme.__instance is None:
            Theme.__instance = cls(engine)
        return Theme.__instance 
Example #4
Source File: desktop.py    From gridsync with GNU General Public License v3.0 5 votes vote down vote up
def set_clipboard_text(text, mode=QClipboard.Clipboard):
    QCoreApplication.instance().clipboard().setText(text, mode)
    logging.debug(
        "Copied %i bytes to clipboard %i", len(text) if text else 0, mode
    ) 
Example #5
Source File: desktop.py    From gridsync with GNU General Public License v3.0 5 votes vote down vote up
def get_clipboard_text(mode=QClipboard.Clipboard):
    return QCoreApplication.instance().clipboard().text(mode) 
Example #6
Source File: desktop.py    From gridsync with GNU General Public License v3.0 5 votes vote down vote up
def get_clipboard_modes():
    clipboard = QCoreApplication.instance().clipboard()
    modes = [QClipboard.Clipboard]
    if clipboard.supportsSelection():
        modes.append(QClipboard.Selection)
    if clipboard.supportsFindBuffer():
        modes.append(QClipboard.FindBuffer)
    return modes 
Example #7
Source File: queue.py    From artisan with GNU General Public License v3.0 5 votes vote down vote up
def __init__(self):
        threading.Thread.__init__(self)
        self.daemon = True  # OK for main to exit even if instance is still running
        self.paused = False  # start out non-paused
        self.state = threading.Condition() 
Example #8
Source File: demo_app1.py    From face-identification-tpe with MIT License 5 votes vote down vote up
def initUI(self):
        self.setGeometry(300, 300, 1280, 720)
        self.setWindowTitle('Face verification demo 1')

        self.l1_btn = QPushButton('Load 1...')
        self.l2_btn = QPushButton('Load 2...')

        self.match_btn = QPushButton('Match')
        self.exit_btn = QPushButton('Exit')

        self.i_lbl[0] = QLabel()
        self.i_lbl[1] = QLabel()

        self.exit_btn.clicked.connect(QCoreApplication.instance().quit)
        self.l1_btn.clicked.connect(self.l1_clicked)
        self.l2_btn.clicked.connect(self.l2_clicked)
        self.match_btn.clicked.connect(self.match_clicked)

        hbox = QHBoxLayout()
        hbox.addWidget(self.l1_btn)
        hbox.addWidget(self.l2_btn)
        hbox.addStretch(1)
        hbox.addWidget(self.match_btn)
        hbox.addStretch(1)
        hbox.addWidget(self.exit_btn)

        hbox2 = QHBoxLayout()
        hbox2.addWidget(self.i_lbl[0])
        hbox2.addStretch(1)
        hbox2.addWidget(self.i_lbl[1])

        vbox = QVBoxLayout()
        vbox.addStretch(1)
        vbox.addLayout(hbox2)
        vbox.addStretch(1)
        vbox.addLayout(hbox)

        self.setLayout(vbox)

        self.show() 
Example #9
Source File: Closing_a_window.py    From python with Apache License 2.0 5 votes vote down vote up
def initUI(self):               
        
        qbtn = QPushButton('Quit', self)
        qbtn.clicked.connect(QCoreApplication.instance().quit) # 事件传递
        qbtn.resize(qbtn.sizeHint())
        qbtn.move(50, 50)       
        
        self.setGeometry(300, 300, 250, 150)
        self.setWindowTitle('Quit button')    
        self.show() 
Example #10
Source File: QtApplication.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def getInstance(cls, *args, **kwargs) -> "QtApplication":
        """Gets the instance of this application.

        This is just to further specify the type of Application.getInstance().
        :return: The instance of this application.
        """

        return cast(QtApplication, super().getInstance(**kwargs)) 
Example #11
Source File: QtApplication.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def createQmlComponent(self, qml_file_path: str, context_properties: Dict[str, "QObject"] = None) -> Optional["QObject"]:
        """Create a QML component from a qml file.
        :param qml_file_path:: The absolute file path to the root qml file.
        :param context_properties:: Optional dictionary containing the properties that will be set on the context of the
        qml instance before creation.
        :return: None in case the creation failed (qml error), else it returns the qml instance.
        :note If the creation fails, this function will ensure any errors are logged to the logging service.
        """

        if self._qml_engine is None: # Protect in case the engine was not initialized yet
            return None
        path = QUrl.fromLocalFile(qml_file_path)
        component = QQmlComponent(self._qml_engine, path)
        result_context = QQmlContext(self._qml_engine.rootContext()) #type: ignore #MyPy doens't realise that self._qml_engine can't be None here.
        if context_properties is not None:
            for name, value in context_properties.items():
                result_context.setContextProperty(name, value)
        result = component.create(result_context)
        for err in component.errors():
            Logger.log("e", str(err.toString()))
        if result is None:
            return None

        # We need to store the context with the qml object, else the context gets garbage collected and the qml objects
        # no longer function correctly/application crashes.
        result.attached_context = result_context
        return result 
Example #12
Source File: Theme.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _initializeDefaults(self) -> None:
        self._fonts = {
            "system": QCoreApplication.instance().font(),
            "fixed": QFontDatabase.systemFont(QFontDatabase.FixedFont)
        }

        palette = QCoreApplication.instance().palette()
        self._colors = {
            "system_window": palette.window(),
            "system_text": palette.text()
        }

        self._sizes = {
            "line": QSizeF(self._em_width, self._em_height)
        } 
Example #13
Source File: Theme.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, engine, parent = None) -> None:
        super().__init__(parent)

        self._engine = engine
        self._styles = None  # type: Optional[QObject]
        self._path = ""
        self._icons = {}  # type: Dict[str, QUrl]
        self._images = {}  # type: Dict[str, QUrl]

        # Workaround for incorrect default font on Windows
        if sys.platform == "win32":
            default_font = QFont()
            default_font.setPointSize(9)
            QCoreApplication.instance().setFont(default_font)

        self._em_height = int(QFontMetrics(QCoreApplication.instance().font()).ascent())
        self._em_width = self._em_height

        # Cache the initial language in the preferences. For fonts, a special font can be defined with, for example,
        # "medium" and "medium_nl_NL". If the special one exists, getFont() will return that, otherwise the default
        # will be returned. We cache the initial language here is because Cura can only change its language if it gets
        # restarted, so we need to keep the fonts consistent in a single Cura run.
        self._preferences = UM.Application.Application.getInstance().getPreferences()
        self._lang_code = self._preferences.getValue("general/language")

        self._initializeDefaults()

        self.reload() 
Example #14
Source File: TaskManager.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _onDelayReached(self, event: "_CallFunctionEvent") -> None:
        QCoreApplication.instance().postEvent(self, event)

    # Handle Qt events 
Example #15
Source File: TaskManager.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def callLater(self, delay: float, callback: Callable, *args, **kwargs) -> None:
        if delay < 0:
            raise ValueError("delay must be a non-negative value, but got [%s] instead." % delay)

        delay_to_use = None if delay <= 0 else delay
        event = _CallFunctionEvent(self, callback, args, kwargs,
                                   delay = delay_to_use)
        if delay_to_use is None:
            QCoreApplication.instance().postEvent(self, event)
        else:
            self._scheduleDelayedCallEvent(event) 
Example #16
Source File: TaskManager.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def cleanup(self) -> None:
        for event in list(self._delayed_events.keys()):
            self._cleanupDelayedCallEvent(event)
        self._delayed_events.clear()

        # Removes all events that have been posted to the QApplication.
        QCoreApplication.instance().removePostedEvents(None, self._event_type)

    # Schedules a callback function to be called later. If delay is given, the callback will be scheduled to call after
    # the given amount of time. Otherwise, the callback will be scheduled to the QCoreApplication instance to be called
    # the next time the event gets picked up. 
Example #17
Source File: TaskManager.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def event_type(self) -> int:
        return self._event_type

    # Cleans up all the delayed events and remove all events that were posted by this TaskManager instance. 
Example #18
Source File: TaskManager.py    From Uranium with GNU Lesser General Public License v3.0 5 votes vote down vote up
def callFunction(self) -> None:
        self._function(*self._args, **self._kwargs)


#
#
# This is not a singleton class. The TaskManager is intended to make it easier for certain task-management-ish classes
# to handle tasks within the Qt event loop framework. It makes it easier to:
#
#  - Schedule a callback that will be picked up by the Qt event loop later.
#  - Schedule a callback with a delay (given in seconds).
#  - Remove all callbacks that has been scheduled but not yet invoked.
#
# This class uses QEvent, unique QEvent types, and QCoreApplication::postEvent() to achieve those functionality. A
# unique QEvent type is assigned for each TaskManager instance, so each instance can cancel the QEvent posted by itself.
# The unique QEvent type is retrieved via QEvent.registerEventType(), which will return a unique custom event type if
# available. If no more custom event type is available, it will return -1. A custom/user event type is a number between
# QEvent::User (1000) and QEvent::MaxUser (65535). See https://doc.qt.io/qt-5/qevent.html
#
# Here we use QCoreApplication.removePostedEvents() to remove posted but not yet dispatched events. Those are the events
# that have been posted but not yet processed. You can consider this as cancelling a task that you have scheduled
# earlier but it has not yet been executed. Because QCoreApplication.removePostedEvents() can use an eventType argument
# to specify the event type you want to remove, here we use that unique custom event type for each TaskManager to
# identify all events that are managed by the TaskManager itself. See https://doc.qt.io/qt-5/qcoreapplication.html
#
# According to my experience, QTimer doesn't seem to trigger events very accurately. I had for example, an expected
# delay of 5.0 seconds, but I got an actual delay of 4.7 seconds. That's around 6% off. So, here we add a little
# tolerance to all the specified delay.
# 
Example #19
Source File: quickplotter.py    From phidl with MIT License 4 votes vote down vote up
def quickplot2(item_list, *args, **kwargs):
    if qt_imported == False:
        raise ImportError("PHIDL tried to import PyQt5 but it failed. PHIDL will" + 
              "still work but quickplot2() may not.  Try using" +
              "quickplot() instead (based on matplotlib)")
        
    global app
    if QCoreApplication.instance() is None:
        app = QApplication(sys.argv)
    if 'viewer_window' not in globals():
        global viewer_window
        viewer_window = ViewerWindow()
    viewer = viewer_window.viewer
    viewer.initialize()
    if type(item_list) not in (list, tuple):
        item_list = [item_list]
    for element in item_list:
        if isinstance(element, (phidl.device_layout.Device, phidl.device_layout.DeviceReference, gdspy.CellArray)):
            # Draw polygons in the element
            polygons_spec = element.get_polygons(by_spec=True, depth=None)
            for key in sorted(polygons_spec):
                polygons = polygons_spec[key]
                layerprop = _get_layerprop(layer = key[0], datatype = key[1])
                viewer.add_polygons(polygons, color = layerprop['color'], alpha = layerprop['alpha'])
            # If element is a Device, draw ports and aliases
            if isinstance(element, phidl.device_layout.Device):
                for ref in element.references:
                    if not isinstance(ref, gdspy.CellArray):
                        for name, port in ref.ports.items():
                            viewer.add_port(port, is_subport = True)
                for name, port in element.ports.items():
                    viewer.add_port(port)
                    viewer.add_aliases(element.aliases)
            # If element is a DeviceReference, draw ports as subports
            if isinstance(element, phidl.device_layout.DeviceReference):
                for name, port in element.ports.items():
                    viewer.add_port(port, is_subport = True)
        elif isinstance(element, (phidl.device_layout.Polygon)):
                layerprop = _get_layerprop(layer = element.layers[0], datatype = element.datatypes[0])
                viewer.add_polygons(element.polygons, color = layerprop['color'], alpha = layerprop['alpha'])
    viewer.finalize()
    viewer.reset_view()
    viewer_window.setVisible(True)
    viewer_window.show()
    viewer_window.raise_()
    return viewer