Python PyQt5.QtCore.QObject() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.QObject(). These examples are extracted from open source projects. 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 check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PyQt5.QtCore , or try the search function .

Example 1
Project: qutebrowser   Author: qutebrowser   File: test_debug.py    License: GNU General Public License v3.0 6 votes vote down vote up
def test_get_all_objects(self, stubs, monkeypatch):
        # pylint: disable=unused-variable
        widgets = [self.Object('Widget 1'), self.Object('Widget 2')]
        app = stubs.FakeQApplication(all_widgets=widgets)
        monkeypatch.setattr(debug, 'QApplication', app)

        root = QObject()
        o1 = self.Object('Object 1', root)
        o2 = self.Object('Object 2', o1)  # noqa: F841
        o3 = self.Object('Object 3', root)  # noqa: F841

        expected = textwrap.dedent("""
            Qt widgets - 2 objects:
                <Widget 1>
                <Widget 2>

            Qt objects - 3 objects:
                <Object 1>
                    <Object 2>
                <Object 3>

            global object registry - 0 objects:
        """).rstrip('\n')

        assert debug.get_all_objects(start_obj=root) == expected 
Example 2
Project: qutebrowser   Author: qutebrowser   File: objreg.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __setitem__(self, name: _IndexType, obj: typing.Any) -> None:
        """Register an object in the object registry.

        Sets a slot to remove QObjects when they are destroyed.
        """
        if name is None:
            raise TypeError("Registering '{}' with name 'None'!".format(obj))
        if obj is None:
            raise TypeError("Registering object None with name '{}'!".format(
                name))

        self._disconnect_destroyed(name)

        if isinstance(obj, QObject):
            func = functools.partial(self.on_destroyed, name)
            obj.destroyed.connect(func)
            self._partial_objs[name] = func

        super().__setitem__(name, obj) 
Example 3
Project: qutebrowser   Author: qutebrowser   File: debug.py    License: GNU General Public License v3.0 6 votes vote down vote up
def get_all_objects(start_obj: QObject = None) -> str:
    """Get all children of an object recursively as a string."""
    output = ['']
    widget_lines = _get_widgets()
    widget_lines = ['    ' + e for e in widget_lines]
    widget_lines.insert(0, "Qt widgets - {} objects:".format(
        len(widget_lines)))
    output += widget_lines

    if start_obj is None:
        start_obj = QApplication.instance()

    pyqt_lines = []  # type: typing.List[str]
    _get_pyqt_objects(pyqt_lines, start_obj)
    pyqt_lines = ['    ' + e for e in pyqt_lines]
    pyqt_lines.insert(0, 'Qt objects - {} objects:'.format(len(pyqt_lines)))

    output += ['']
    output += pyqt_lines
    output += objreg.dump_objects()
    return '\n'.join(output) 
Example 4
Project: qutebrowser   Author: qutebrowser   File: throttle.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self,
                 func: typing.Callable,
                 delay_ms: int,
                 parent: QObject = None) -> None:
        """Constructor.

        Args:
            delay_ms: The time to wait before allowing another call of the
                         function. -1 disables the wrapper.
            func: The function/method to call on __call__.
            parent: The parent object.
        """
        super().__init__(parent)
        self._delay_ms = delay_ms
        self._func = func
        self._pending_call = None  # type: typing.Optional[_CallArgs]
        self._last_call_ms = None  # type: typing.Optional[int]
        self._timer = usertypes.Timer(self, 'throttle-timer')
        self._timer.setSingleShot(True) 
Example 5
Project: qutebrowser   Author: qutebrowser   File: stylesheet.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, obj: QObject,
                 stylesheet: Optional[str], update: bool) -> None:
        super().__init__()
        self._obj = obj
        self._update = update

        # We only need to hang around if we are asked to update.
        if update:
            self.setParent(self._obj)
        if stylesheet is None:
            self._stylesheet = obj.STYLESHEET  # type: str
        else:
            self._stylesheet = stylesheet

        if update:
            self._options = jinja.template_config_variables(
                self._stylesheet)  # type: Optional[FrozenSet[str]]
        else:
            self._options = None 
Example 6
Project: Cura   Author: Ultimaker   File: NetworkedPrinterOutputDevice.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, device_id, address: str, properties: Dict[bytes, bytes], connection_type: ConnectionType = ConnectionType.NetworkConnection, parent: QObject = None) -> None:
        super().__init__(device_id = device_id, connection_type = connection_type, parent = parent)
        self._manager = None    # type: Optional[QNetworkAccessManager]
        self._timeout_time = 10  # After how many seconds of no response should a timeout occur?

        self._last_response_time = None     # type: Optional[float]
        self._last_request_time = None      # type: Optional[float]

        self._api_prefix = ""
        self._address = address
        self._properties = properties
        self._user_agent = "%s/%s " % (CuraApplication.getInstance().getApplicationName(),
                                       CuraApplication.getInstance().getVersion())

        self._onFinishedCallbacks = {}      # type: Dict[str, Callable[[QNetworkReply], None]]
        self._authentication_state = AuthState.NotAuthenticated

        # QHttpMultiPart objects need to be kept alive and not garbage collected during the
        # HTTP which uses them. We hold references to these QHttpMultiPart objects here.
        self._kept_alive_multiparts = {}        # type: Dict[QNetworkReply, QHttpMultiPart]

        self._sending_gcode = False
        self._compressing_gcode = False
        self._gcode = []                    # type: List[str]
        self._connection_state_before_timeout = None    # type: Optional[ConnectionState] 
Example 7
Project: Cura   Author: Ultimaker   File: WelcomePagesModel.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, application: "CuraApplication", parent: Optional["QObject"] = None) -> None:
        super().__init__(parent)

        self.addRoleName(self.IdRole, "id")
        self.addRoleName(self.PageUrlRole, "page_url")
        self.addRoleName(self.NextPageIdRole, "next_page_id")
        self.addRoleName(self.NextPageButtonTextRole, "next_page_button_text")
        self.addRoleName(self.PreviousPageButtonTextRole, "previous_page_button_text")

        self._application = application
        self._catalog = i18nCatalog("cura")

        self._default_next_button_text = self._catalog.i18nc("@action:button", "Next")

        self._pages = []  # type: List[Dict[str, Any]]

        self._current_page_index = 0
        # Store all the previous page indices so it can go back.
        self._previous_page_indices_stack = deque()  # type: deque

        # If the welcome flow should be shown. It can show the complete flow or just the changelog depending on the
        # specific case. See initialize() for how this variable is set.
        self._should_show_welcome_flow = False 
Example 8
Project: Cura   Author: Ultimaker   File: MachineActionManager.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, application: "CuraApplication", parent: Optional["QObject"] = None) -> None:
        super().__init__(parent = parent)
        self._application = application
        self._container_registry = self._application.getContainerRegistry()

        # Keeps track of which machines have already been processed so we don't do that again.
        self._definition_ids_with_default_actions_added = set()  # type: Set[str]

        # Dict of all known machine actions
        self._machine_actions = {}  # type: Dict[str, MachineAction]
        # Dict of all required actions by definition ID
        self._required_actions = {}  # type: Dict[str, List[MachineAction]]
        # Dict of all supported actions by definition ID
        self._supported_actions = {}  # type: Dict[str, List[MachineAction]]
        # Dict of all actions that need to be done when first added by definition ID
        self._first_start_actions = {}  # type: Dict[str, List[MachineAction]] 
Example 9
Project: Cura   Author: Ultimaker   File: IntentModel.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, parent: Optional[QObject] = None) -> None:
        super().__init__(parent)

        self.addRoleName(self.NameRole, "name")
        self.addRoleName(self.QualityTypeRole, "quality_type")
        self.addRoleName(self.LayerHeightRole, "layer_height")
        self.addRoleName(self.AvailableRole, "available")
        self.addRoleName(self.IntentRole, "intent_category")

        self._intent_category = "engineering"

        self._update_timer = QTimer()
        self._update_timer.setInterval(100)
        self._update_timer.setSingleShot(True)
        self._update_timer.timeout.connect(self._update)

        machine_manager = cura.CuraApplication.CuraApplication.getInstance().getMachineManager()
        machine_manager.globalContainerChanged.connect(self._updateDelayed)
        machine_manager.extruderChanged.connect(self._updateDelayed)  # We also need to update if an extruder gets disabled
        ContainerRegistry.getInstance().containerAdded.connect(self._onChanged)
        ContainerRegistry.getInstance().containerRemoved.connect(self._onChanged)
        self._layer_height_unit = ""  # This is cached
        self._update() 
Example 10
Project: Cura   Author: Ultimaker   File: LocalClusterOutputDevice.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, device_id: str, address: str, properties: Dict[bytes, bytes], parent=None) -> None:

        super().__init__(
            device_id=device_id,
            address=address,
            properties=properties,
            connection_type=ConnectionType.NetworkConnection,
            parent=parent
        )

        self._cluster_api = None  # type: Optional[ClusterApiClient]
        self._active_exported_job = None  # type: Optional[ExportFileJob]
        self._printer_select_dialog = None  # type: Optional[QObject]

        # We don't have authentication over local networking, so we're always authenticated.
        self.setAuthenticationState(AuthState.Authenticated)
        self._setInterfaceElements()
        self._active_camera_url = QUrl()  # type: QUrl 
Example 11
Project: Cura   Author: Ultimaker   File: LicensePresenter.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, app: CuraApplication) -> None:
        super().__init__()
        self._presented = False
        """Whether present() has been called and state is expected to be initialized"""
        self._catalog = i18nCatalog("cura")
        self._dialog = None  # type: Optional[QObject]
        self._package_manager = app.getPackageManager()  # type: PackageManager
        # Emits List[Dict[str, [Any]] containing for example
        # [{ "package_id": "BarbarianPlugin", "package_path" : "/tmp/dg345as", "accepted" : True }]
        self.licenseAnswers = Signal()

        self._current_package_idx = 0
        self._package_models = []  # type: List[Dict]
        decline_button_text = self._catalog.i18nc("@button", "Decline and remove from account")
        self._license_model = LicenseModel(decline_button_text=decline_button_text)  # type: LicenseModel
        self._page_count = 0

        self._app = app

        self._compatibility_dialog_path = "resources/qml/dialogs/ToolboxLicenseDialog.qml" 
Example 12
Project: Cura   Author: Ultimaker   File: MachineSettingsAction.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, parent: Optional["QObject"] = None) -> None:
        super().__init__("MachineSettingsAction", catalog.i18nc("@action", "Machine Settings"))
        self._qml_url = "MachineSettingsAction.qml"

        from cura.CuraApplication import CuraApplication
        self._application = CuraApplication.getInstance()

        from cura.Settings.CuraContainerStack import _ContainerIndexes
        self._store_container_index = _ContainerIndexes.DefinitionChanges

        self._container_registry = ContainerRegistry.getInstance()
        self._container_registry.containerAdded.connect(self._onContainerAdded)

        # The machine settings dialog blocks auto-slicing when it's shown, and re-enables it when it's finished.
        self._backend = self._application.getBackend()
        self.onFinished.connect(self._onFinished)

        # If the g-code flavour changes between UltiGCode and another flavour, we need to update the container tree.
        self._application.globalContainerStackChanged.connect(self._updateHasMaterialsInContainerTree)

    # Which container index in a stack to store machine setting changes. 
Example 13
Project: kite   Author: pyrocko   File: tab_covariance.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, model, parent):
        QtCore.QObject.__init__(self)
        self.sigCalculateWeightMatrix.connect(
            model.calculateWeightMatrix)

        diag = QtGui.QMessageBox.information(
            parent,
            'Calculate Full Weight Matrix',
            '''<html><head/><body><p>
This will calculate the quadtree's full weight matrix
(<span style='font-family: monospace'>Covariance.weight_matrix</span>)
for this noise/covariance configuration.</p><p>
The calculation is expensive and may take several minutes.
</p></body></html>
''', buttons=(QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel))

        if diag == QtGui.QMessageBox.Ok:
            meta = model.metaObject()
            meta.invokeMethod(
                model, 'calculateWeightMatrix',
                QtCore.Qt.QueuedConnection) 
Example 14
Project: kite   Author: pyrocko   File: sandbox_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, sandbox_model=None, *args, **kwargs):
        QtCore.QObject.__init__(self)

        self.model = sandbox_model
        self.log = SceneLogModel(self)
        self.sources = SourceModel(self)
        self.cursor_tracker = CursorTracker(self)

        self._log_handler = logging.Handler()
        self._log_handler.setLevel(logging.DEBUG)
        self._log_handler.emit = self.sigLogRecord.emit

        logging.root.setLevel(logging.DEBUG)
        logging.root.addHandler(self._log_handler)

        self.worker_thread = QtCore.QThread()
        self.moveToThread(self.worker_thread)
        self.worker_thread.start()

        if self.model:
            self.setModel(self.model) 
Example 15
Project: Uranium   Author: Ultimaker   File: Duration.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def __init__(self, duration: Optional[int] = None, parent = None) -> None:
        """Create a duration object.

        :param duration: The duration in seconds. If this is None (the default), an invalid Duration object will be created.
        :param parent: The QObject parent.
        """

        super().__init__(parent)

        self._days = -1
        self._hours = -1
        self._minutes = -1
        self._seconds = -1

        if duration is not None:
            self.setDuration(duration) 
Example 16
Project: dcc   Author: amimo   File: HexViewMode.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, view, widget):
        super(QtCore.QObject, self).__init__()
        self.widget = widget
        self.view = view 
Example 17
Project: qutebrowser   Author: qutebrowser   File: test_throttle.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_deleted_object(qtbot):
    class Obj(QObject):

        def func(self):
            self.setObjectName("test")

    obj = Obj()

    throttled = throttle.Throttle(obj.func, DELAY, parent=obj)
    throttled()
    throttled()

    sip.delete(obj)

    qtbot.wait(int(1.5 * DELAY)) 
Example 18
Project: qutebrowser   Author: qutebrowser   File: usertypes.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QObject = None) -> None:
        super().__init__(parent)
        self.mode = None  # type: typing.Optional[PromptMode]
        self.default = None  # type: typing.Union[bool, str, None]
        self.title = None  # type: typing.Optional[str]
        self.text = None  # type: typing.Optional[str]
        self.url = None  # type: typing.Optional[str]
        self.option = None  # type: typing.Optional[bool]
        self.answer = None  # type: typing.Union[str, bool, None]
        self.is_aborted = False
        self.interrupted = False 
Example 19
Project: qutebrowser   Author: qutebrowser   File: usertypes.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QObject = None, name: str = None) -> None:
        super().__init__(parent)
        if name is None:
            self._name = "unnamed"
        else:
            self.setObjectName(name)
            self._name = name 
Example 20
Project: qutebrowser   Author: qutebrowser   File: objreg.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _on_destroyed(self, name: str) -> None:
        """Remove a destroyed QObject."""
        log.destroy.debug("removed: {}".format(name))
        if not hasattr(self, 'data'):
            # This sometimes seems to happen on CI during
            # test_history.test_adding_item_during_async_read
            # and I have no idea why...
            return
        try:
            del self[name]
            del self._partial_objs[name]
        except KeyError:
            pass 
Example 21
Project: qutebrowser   Author: qutebrowser   File: message.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QObject = None) -> None:
        super().__init__(parent)
        self._connected = False
        self._cache = [
        ]  # type: typing.List[typing.Tuple[usertypes.MessageLevel, str, bool]] 
Example 22
Project: qutebrowser   Author: qutebrowser   File: debug.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _get_pyqt_objects(lines: typing.MutableSequence[str],
                      obj: QObject,
                      depth: int = 0) -> None:
    """Recursive method for get_all_objects to get Qt objects."""
    for kid in obj.findChildren(QObject, '', Qt.FindDirectChildrenOnly):
        lines.append('    ' * depth + repr(kid))
        _get_pyqt_objects(lines, kid, depth + 1) 
Example 23
Project: qutebrowser   Author: qutebrowser   File: inspector.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, win_id: int, parent: QObject) -> None:
        super().__init__(parent)
        self._win_id = win_id 
Example 24
Project: qutebrowser   Author: qutebrowser   File: inspector.py    License: GNU General Public License v3.0 5 votes vote down vote up
def eventFilter(self, _obj: QObject, event: QEvent) -> bool:
        """Enter insert mode if the inspector is clicked."""
        if event.type() == QEvent.MouseButtonPress:
            modeman.enter(self._win_id, usertypes.KeyMode.insert,
                          reason='Inspector clicked', only_if_normal=True)
        return False 
Example 25
Project: qutebrowser   Author: qutebrowser   File: hints.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, win_id: int, parent: QObject = None) -> None:
        """Constructor."""
        super().__init__(parent)
        self._win_id = win_id
        self._context = None  # type: typing.Optional[HintContext]
        self._word_hinter = WordHinter()

        self._actions = HintActions(win_id)

        mode_manager = modeman.instance(self._win_id)
        mode_manager.left.connect(self.on_mode_left) 
Example 26
Project: qutebrowser   Author: qutebrowser   File: quitter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *,
                 args: argparse.Namespace,
                 parent: QObject = None) -> None:
        super().__init__(parent)
        self.quit_status = {
            'crash': True,
            'tabs': False,
            'main': False,
        }
        self._is_shutting_down = False
        self._args = args 
Example 27
Project: qutebrowser   Author: qutebrowser   File: eventfilter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: QObject = None) -> None:
        super().__init__(parent)
        self._activated = True
        self._handlers = {
            QEvent.KeyPress: self._handle_key_event,
            QEvent.KeyRelease: self._handle_key_event,
            QEvent.ShortcutOverride: self._handle_key_event,
        } 
Example 28
Project: qutebrowser   Author: qutebrowser   File: eventfilter.py    License: GNU General Public License v3.0 5 votes vote down vote up
def eventFilter(self, obj: QObject, event: QEvent) -> bool:
        """Handle an event.

        Args:
            obj: The object which will get the event.
            event: The QEvent which is about to be delivered.

        Return:
            True if the event should be filtered, False if it's passed through.
        """
        if not isinstance(obj, QWindow):
            # We already handled this same event at some point earlier, so
            # we're not interested in it anymore.
            return False

        typ = event.type()

        if typ not in self._handlers:
            return False

        if not self._activated:
            return False

        handler = self._handlers[typ]
        try:
            return handler(typing.cast(QKeyEvent, event))
        except:
            # If there is an exception in here and we leave the eventfilter
            # activated, we'll get an infinite loop and a stack overflow.
            self._activated = False
            raise 
Example 29
Project: qutebrowser   Author: qutebrowser   File: modeparsers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *, mode: usertypes.KeyMode,
                 win_id: int,
                 commandrunner: 'runners.CommandRunner',
                 parent: QObject = None,
                 do_log: bool = True,
                 passthrough: bool = False,
                 supports_count: bool = True) -> None:
        super().__init__(mode=mode, win_id=win_id, parent=parent,
                         do_log=do_log, passthrough=passthrough,
                         supports_count=supports_count)
        self._commandrunner = commandrunner 
Example 30
Project: qutebrowser   Author: qutebrowser   File: modeparsers.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *, win_id: int,
                 commandrunner: 'runners.CommandRunner',
                 parent: QObject = None) -> None:
        super().__init__(mode=usertypes.KeyMode.normal, win_id=win_id,
                         commandrunner=commandrunner, parent=parent)
        self._partial_timer = usertypes.Timer(self, 'partial-match')
        self._partial_timer.setSingleShot(True)
        self._partial_timer.timeout.connect(self._clear_partial_match)
        self._inhibited = False
        self._inhibited_timer = usertypes.Timer(self, 'normal-inhibited')
        self._inhibited_timer.setSingleShot(True)