Python PyQt5.QtCore.QObject() Examples

The following are 30 code examples of PyQt5.QtCore.QObject(). 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 , or try the search function .
Example #1
Source File: Duration.py    From Uranium with 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 #2
Source File: debug.py    From qutebrowser with 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 #3
Source File: objreg.py    From qutebrowser with 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 #4
Source File: test_debug.py    From qutebrowser with 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 #5
Source File: throttle.py    From qutebrowser with 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 #6
Source File: stylesheet.py    From qutebrowser with 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 #7
Source File: NetworkedPrinterOutputDevice.py    From Cura with 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 #8
Source File: WelcomePagesModel.py    From Cura with 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 #9
Source File: MachineActionManager.py    From Cura with 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 #10
Source File: IntentModel.py    From Cura with 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 #11
Source File: LocalClusterOutputDevice.py    From Cura with 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 #12
Source File: LicensePresenter.py    From Cura with 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 #13
Source File: MachineSettingsAction.py    From Cura with 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 #14
Source File: tab_covariance.py    From kite with 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 #15
Source File: sandbox_model.py    From kite with 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 #16
Source File: Toolbox.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def setActivePackage(self, package: QObject) -> None:
        if self._active_package != package:
            self._active_package = package
            self.activePackageChanged.emit() 
Example #17
Source File: Toolbox.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _createDialog(self, qml_name: str) -> Optional[QObject]:
        Logger.log("d", "Marketplace: Creating dialog [%s].", qml_name)
        plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
        if not plugin_path:
            return None
        path = os.path.join(plugin_path, "resources", "qml", qml_name)

        dialog = self._application.createQmlComponent(path, {
            "toolbox": self,
            "handler": self,
            "licenseModel": self._license_model
        })
        if not dialog:
            return None
        return dialog 
Example #18
Source File: objreg.py    From qutebrowser with 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 #19
Source File: ImageReaderUI.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def onDepthChanged(self, value):
        if self._ui_view and not self._disable_size_callbacks:
            if len(value) > 0:
                try:
                    self._depth = float(value.replace(",", "."))
                except ValueError:  # Can happen with incomplete numbers, such as "-".
                    self._depth = 0
            else:
                self._depth = 0

            self._width = self._depth * self._aspect
            self._disable_size_callbacks = True
            self._ui_view.findChild(QObject, "Width").setProperty("text", str(self._width))
            self._disable_size_callbacks = False 
Example #20
Source File: ImageReaderUI.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def onWidthChanged(self, value):
        if self._ui_view and not self._disable_size_callbacks:
            if len(value) > 0:
                try:
                    self._width = float(value.replace(",", "."))
                except ValueError:  # Can happen with incomplete numbers, such as "-".
                    self._width = 0
            else:
                self._width = 0

            self._depth = self._width / self._aspect
            self._disable_size_callbacks = True
            self._ui_view.findChild(QObject, "Depth").setProperty("text", str(self._depth))
            self._disable_size_callbacks = False 
Example #21
Source File: utils.py    From MDT with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, queue, *args, **kwargs):
        """A QObject (to be run in a QThread) which sits waiting for data to come through a Queue.Queue().

        It blocks until data is available, and one it has got something from the _logging_update_queue, it sends
        it to the "MainThread" by emitting a Qt Signal.

        Attributes:
            is_running (boolean): set to False to stop the receiver.
        """
        super().__init__(*args, **kwargs)
        self.queue = queue
        self.is_running = True 
Example #22
Source File: ImageReaderUI.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _actualShowConfigUI(self):
        self._disable_size_callbacks = True

        if self._ui_view is None:
            self._createConfigUI()
        self._ui_view.show()

        self._ui_view.findChild(QObject, "Width").setProperty("text", str(self._width))
        self._ui_view.findChild(QObject, "Depth").setProperty("text", str(self._depth))
        self._disable_size_callbacks = False

        self._ui_view.findChild(QObject, "Base_Height").setProperty("text", str(self.base_height))
        self._ui_view.findChild(QObject, "Peak_Height").setProperty("text", str(self.peak_height))
        self._ui_view.findChild(QObject, "Transmittance").setProperty("text", str(self.transmittance_1mm))
        self._ui_view.findChild(QObject, "Smoothing").setProperty("value", self.smoothing) 
Example #23
Source File: MachineAction.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def _createViewFromQML(self) -> Optional["QObject"]:
        """Protected helper to create a view object based on provided QML."""

        plugin_path = PluginRegistry.getInstance().getPluginPath(self.getPluginId())
        if plugin_path is None:
            Logger.log("e", "Cannot create QML view: cannot find plugin path for plugin [%s]", self.getPluginId())
            return None
        path = os.path.join(plugin_path, self._qml_url)

        from cura.CuraApplication import CuraApplication
        view = CuraApplication.getInstance().createQmlComponent(path, {"manager": self})
        return view 
Example #24
Source File: NetworkingUtil.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: Optional["QObject"] = None) -> None:
        super().__init__(parent = parent)

    # Checks if the given string is a valid IPv4 address. 
Example #25
Source File: CuraPackageManager.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, application: "QtApplication", parent: Optional["QObject"] = None) -> None:
        super().__init__(application, parent) 
Example #26
Source File: MachineErrorChecker.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: Optional[QObject] = None) -> None:
        super().__init__(parent)

        self._global_stack = None

        self._has_errors = True  # Result of the error check, indicating whether there are errors in the stack
        self._error_keys = set()  # type: Set[str] # A set of settings keys that have errors
        self._error_keys_in_progress = set()  # type: Set[str]  # The variable that stores the results of the currently in progress check

        self._stacks_and_keys_to_check = None  # type: Optional[deque]  # a FIFO queue of tuples (stack, key) to check for errors

        self._need_to_check = False  # Whether we need to schedule a new check or not. This flag is set when a new
                                     # error check needs to take place while there is already one running at the moment.
        self._check_in_progress = False  # Whether there is an error check running in progress at the moment.

        self._application = cura.CuraApplication.CuraApplication.getInstance()
        self._machine_manager = self._application.getMachineManager()

        self._start_time = 0.  # measure checking time

        # This timer delays the starting of error check so we can react less frequently if the user is frequently
        # changing settings.
        self._error_check_timer = QTimer(self)
        self._error_check_timer.setInterval(100)
        self._error_check_timer.setSingleShot(True)

        self._keys_to_check = set()  # type: Set[str] 
Example #27
Source File: CustomQualityProfilesDropDownMenuModel.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: Optional["QObject"] = None) -> None:
        super().__init__(parent)

        container_registry = cura.CuraApplication.CuraApplication.getInstance().getContainerRegistry()
        container_registry.containerAdded.connect(self._qualityChangesListChanged)
        container_registry.containerRemoved.connect(self._qualityChangesListChanged)
        container_registry.containerMetaDataChanged.connect(self._qualityChangesListChanged) 
Example #28
Source File: hints.py    From qutebrowser with 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 #29
Source File: QualityManagementModel.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, parent: Optional["QObject"] = None) -> None:
        super().__init__(parent)

        self.addRoleName(self.NameRole, "name")
        self.addRoleName(self.IsReadOnlyRole, "is_read_only")
        self.addRoleName(self.QualityGroupRole, "quality_group")
        self.addRoleName(self.QualityTypeRole, "quality_type")
        self.addRoleName(self.QualityChangesGroupRole, "quality_changes_group")
        self.addRoleName(self.IntentCategoryRole, "intent_category")
        self.addRoleName(self.SectionNameRole, "section_name")

        application = cura.CuraApplication.CuraApplication.getInstance()
        container_registry = application.getContainerRegistry()
        self._machine_manager = application.getMachineManager()
        self._machine_manager.activeQualityGroupChanged.connect(self._onChange)
        self._machine_manager.activeStackChanged.connect(self._onChange)
        self._machine_manager.extruderChanged.connect(self._onChange)
        self._machine_manager.globalContainerChanged.connect(self._onChange)

        self._extruder_manager = application.getExtruderManager()
        self._extruder_manager.extrudersChanged.connect(self._onChange)

        container_registry.containerAdded.connect(self._qualityChangesListChanged)
        container_registry.containerRemoved.connect(self._qualityChangesListChanged)
        container_registry.containerMetaDataChanged.connect(self._qualityChangesListChanged)

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

        self._onChange() 
Example #30
Source File: Toolbox.py    From Cura with GNU Lesser General Public License v3.0 5 votes vote down vote up
def activePackage(self) -> Optional[QObject]:
        """The active package is the package that is currently being downloaded"""

        return self._active_package