Python PyQt5.QtCore.pyqtSignal() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.pyqtSignal(). 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: message.py    License: GNU General Public License v3.0 6 votes vote down vote up
def _build_question(title: str,
                    text: str = None, *,
                    mode: usertypes.PromptMode,
                    default: typing.Union[None, bool, str] = None,
                    abort_on: typing.Iterable[pyqtSignal] = (),
                    url: str = None,
                    option: bool = None) -> usertypes.Question:
    """Common function for ask/ask_async."""
    question = usertypes.Question()
    question.title = title
    question.text = text
    question.mode = mode
    question.default = default
    question.url = url

    if option is not None:
        if mode != usertypes.PromptMode.yesno:
            raise ValueError("Can only 'option' with PromptMode.yesno")
        if url is None:
            raise ValueError("Need 'url' given when 'option' is given")
    question.option = option

    for sig in abort_on:
        sig.connect(question.abort)
    return question 
Example 2
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: qt_compat.py    License: MIT License 6 votes vote down vote up
def _setup_pyqt5():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    if QT_API == QT_API_PYQT5:
        from PyQt5 import QtCore, QtGui, QtWidgets
        __version__ = QtCore.PYQT_VERSION_STR
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
    elif QT_API == QT_API_PYSIDE2:
        from PySide2 import QtCore, QtGui, QtWidgets, __version__
    else:
        raise ValueError("Unexpected value for the 'backend.qt5' rcparam")
    _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName

    def is_pyqt5():
        return True 
Example 3
Project: GraphicDesignPatternByPython   Author: Relph1119   File: qt_compat.py    License: MIT License 6 votes vote down vote up
def _setup_pyqt5():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    if QT_API == QT_API_PYQT5:
        from PyQt5 import QtCore, QtGui, QtWidgets
        __version__ = QtCore.PYQT_VERSION_STR
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
    elif QT_API == QT_API_PYSIDE2:
        from PySide2 import QtCore, QtGui, QtWidgets, __version__
    else:
        raise ValueError("Unexpected value for the 'backend.qt5' rcparam")
    _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName

    def is_pyqt5():
        return True 
Example 4
Project: Uranium   Author: Ultimaker   File: InstanceContainer.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def setName(self, name: str) -> None:
        if name != self.getName():
            self._metadata["name"] = name
            self._dirty = True
            self.nameChanged.emit()
            self.pyqtNameChanged.emit()
            self.metaDataChanged.emit(self)


    # Because we want to expose the properties of InstanceContainer as Qt properties for
    # CURA-3497, the nameChanged signal should be changed to a pyqtSignal. However,
    # pyqtSignal throws TypeError when calling disconnect() when there are no connections.
    # This causes a lot of errors in Cura code when we try to disconnect from nameChanged.
    # Therefore, rather than change the type of nameChanged, we add an extra signal that
    # is used as notify for the property.
    #
    # TODO: Remove this once the Cura code has been refactored to not use nameChanged anymore. 
Example 5
Project: uExport   Author: chrisevans3d   File: Qt.py    License: zlib License 6 votes vote down vote up
def _pyqt5():
    import PyQt5.Qt
    from PyQt5 import QtCore, QtWidgets, uic

    _remap(QtCore, "Signal", QtCore.pyqtSignal)
    _remap(QtCore, "Slot", QtCore.pyqtSlot)
    _remap(QtCore, "Property", QtCore.pyqtProperty)

    _add(PyQt5, "__binding__", PyQt5.__name__)
    _add(PyQt5, "load_ui", lambda fname: uic.loadUi(fname))
    _add(PyQt5, "translate", lambda context, sourceText, disambiguation, n: (
        QtCore.QCoreApplication(context, sourceText,
                                disambiguation, n)))
    _add(PyQt5,
         "setSectionResizeMode",
         QtWidgets.QHeaderView.setSectionResizeMode)

    _maintain_backwards_compatibility(PyQt5)

    return PyQt5 
Example 6
Project: pandasgui   Author: adamerose   File: find_toolbar.py    License: MIT License 6 votes vote down vote up
def update_matches(self, cells_matched):
        '''
        PyQt Slot that updates the matches found each time it gets a signal.

        Args:
            cells_matched: list of tuples - (row, col). Type QtCore.pyqtSignal(list).
        '''
        # converts list of tuples to list of QtCore.QModelIndex for easy selection.
        match_idxs = [self.current_model.index(row, col) for row, col in cells_matched]
        self.search_matches.extend(match_idxs)

        matches_found_text = 'Matches Found: ' + str(len(self.search_matches))
        self.matches_found_label.setText(matches_found_text)

        if self.search_matches and self.search_selection is None:
            # highlight first match
            self.search_selection = 0
            self.highlight_match() 
Example 7
Project: coffeegrindsize   Author: jgagneastro   File: qt_compat.py    License: MIT License 6 votes vote down vote up
def _setup_pyqt5():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    if QT_API == QT_API_PYQT5:
        from PyQt5 import QtCore, QtGui, QtWidgets
        __version__ = QtCore.PYQT_VERSION_STR
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
    elif QT_API == QT_API_PYSIDE2:
        from PySide2 import QtCore, QtGui, QtWidgets, __version__
    else:
        raise ValueError("Unexpected value for the 'backend.qt5' rcparam")
    _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName

    def is_pyqt5():
        return True 
Example 8
Project: CogAlg   Author: boris-kz   File: qt_compat.py    License: MIT License 6 votes vote down vote up
def _setup_pyqt5():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    if QT_API == QT_API_PYQT5:
        from PyQt5 import QtCore, QtGui, QtWidgets
        __version__ = QtCore.PYQT_VERSION_STR
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
    elif QT_API == QT_API_PYSIDE2:
        from PySide2 import QtCore, QtGui, QtWidgets, __version__
    else:
        raise ValueError("Unexpected value for the 'backend.qt5' rcparam")
    _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName

    def is_pyqt5():
        return True 
Example 9
Project: Carnets   Author: holzschu   File: qt_loaders.py    License: BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
def import_pyqt5():
    """
    Import PyQt5

    ImportErrors rasied within this function are non-recoverable
    """

    from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui, QtPrintSupport

    import sip

    # Alias PyQt-specific functions for PySide compatibility.
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot

    # Join QtGui and QtWidgets for Qt4 compatibility.
    QtGuiCompat = types.ModuleType('QtGuiCompat')
    QtGuiCompat.__dict__.update(QtGui.__dict__)
    QtGuiCompat.__dict__.update(QtWidgets.__dict__)
    QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)

    api = QT_API_PYQT5
    return QtCore, QtGuiCompat, QtSvg, api 
Example 10
Project: twitter-stock-recommendation   Author: alvarobartt   File: qt_compat.py    License: MIT License 6 votes vote down vote up
def _setup_pyqt5():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    if QT_API == QT_API_PYQT5:
        from PyQt5 import QtCore, QtGui, QtWidgets
        __version__ = QtCore.PYQT_VERSION_STR
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
    elif QT_API == QT_API_PYSIDE2:
        from PySide2 import QtCore, QtGui, QtWidgets, __version__
    else:
        raise ValueError("Unexpected value for the 'backend.qt5' rcparam")
    _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName

    def is_pyqt5():
        return True 
Example 11
Project: qutebrowser   Author: qutebrowser   File: debug.py    License: GNU General Public License v3.0 5 votes vote down vote up
def dbg_signal(sig: pyqtSignal, args: typing.Any) -> str:
    """Get a string representation of a signal for debugging.

    Args:
        sig: A pyqtSignal.
        args: The arguments as list of strings.

    Return:
        A human-readable string representation of signal/args.
    """
    return '{}({})'.format(signal_name(sig), format_args(args)) 
Example 12
Project: pipeline   Author: liorbenhorin   File: Qt.py    License: MIT License 5 votes vote down vote up
def _pyqt5():
    import PyQt5.Qt
    from PyQt5 import QtCore, QtWidgets, uic

    _remap(QtCore, "Signal", QtCore.pyqtSignal)
    _remap(QtCore, "Slot", QtCore.pyqtSlot)
    _remap(QtCore, "Property", QtCore.pyqtProperty)

    _add(PyQt5, "__binding__", PyQt5.__name__)
    _add(PyQt5, "load_ui", lambda fname: uic.loadUi(fname))
    _add(PyQt5, "translate", lambda context, sourceText, disambiguation, n: (
        QtCore.QCoreApplication(context, sourceText,
                                disambiguation, n)))
    _add(PyQt5,
         "setSectionResizeMode",
         QtWidgets.QHeaderView.setSectionResizeMode)

    _maintain_backwards_compatibility(PyQt5)

    return PyQt5 
Example 13
Project: PyDev.Debugger   Author: fabioz   File: qt_loaders.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def import_pyqt4(version=2):
    """
    Import PyQt4

    Parameters
    ----------
    version : 1, 2, or None
      Which QString/QVariant API to use. Set to None to use the system
      default

    ImportErrors raised within this function are non-recoverable
    """
    # The new-style string API (version=2) automatically
    # converts QStrings to Unicode Python strings. Also, automatically unpacks
    # QVariants to their underlying objects.
    import sip

    if version is not None:
        sip.setapi('QString', version)
        sip.setapi('QVariant', version)

    from PyQt4 import QtGui, QtCore, QtSvg

    if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
        raise ImportError("IPython requires PyQt4 >= 4.7, found %s" %
                          QtCore.PYQT_VERSION_STR)

    # Alias PyQt-specific functions for PySide compatibility.
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot

    # query for the API version (in case version == None)
    version = sip.getapi('QString')
    api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
    return QtCore, QtGui, QtSvg, api 
Example 14
Project: PyDev.Debugger   Author: fabioz   File: qt_loaders.py    License: Eclipse Public License 1.0 5 votes vote down vote up
def import_pyqt5():
    """
    Import PyQt5

    ImportErrors raised within this function are non-recoverable
    """
    from PyQt5 import QtGui, QtCore, QtSvg

    # Alias PyQt-specific functions for PySide compatibility.
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot

    return QtCore, QtGui, QtSvg, QT_API_PYQT5 
Example 15
Project: kite   Author: pyrocko   File: config.py    License: GNU General Public License v3.0 5 votes vote down vote up
def __init__(self, *args, **kwargs):

        class QConfig(QtCore.QObject):
            updated = QtCore.pyqtSignal()

        Object.__init__(self, *args, **kwargs)
        self.qconfig = QConfig() 
Example 16
Project: imperialism-remake   Author: Trilarion   File: qt.py    License: GNU General Public License v3.0 5 votes vote down vote up
def make_widget_clickable(parent):
    """
    Takes any QtWidgets.QWidget derived class and emits a signal emitting on mousePressEvent.
    """

    # noinspection PyPep8Naming
    class ClickableWidgetSubclass(parent):
        """
            A widget that emits a clicked signal when the mouse is pressed.
        """

        #: signal
        clicked = QtCore.pyqtSignal(QtGui.QMouseEvent)

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)

        def mousePressEvent(self, event):  # noqa: N802
            """
            Mouse has been pressed, process the event, then emit the signal.

            :param event:
            """
            super().mousePressEvent(event)
            self.clicked.emit(event)

    return ClickableWidgetSubclass 
Example 17
Project: python3_ios   Author: holzschu   File: qt_compat.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def _setup_pyqt5():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    if QT_API == QT_API_PYQT5:
        from PyQt5 import QtCore, QtGui, QtWidgets
        __version__ = QtCore.PYQT_VERSION_STR
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
    elif QT_API == QT_API_PYSIDE2:
        from PySide2 import QtCore, QtGui, QtWidgets, __version__
    else:
        raise ValueError("Unexpected value for the 'backend.qt5' rcparam")
    _getSaveFileName = QtWidgets.QFileDialog.getSaveFileName

    def is_pyqt5():
        return True 
Example 18
Project: pySINDy   Author: luckystarufo   File: qt_loaders.py    License: MIT License 5 votes vote down vote up
def import_pyqt4(version=2):
    """
    Import PyQt4

    Parameters
    ----------
    version : 1, 2, or None
      Which QString/QVariant API to use. Set to None to use the system
      default

    ImportErrors rasied within this function are non-recoverable
    """
    # The new-style string API (version=2) automatically
    # converts QStrings to Unicode Python strings. Also, automatically unpacks
    # QVariants to their underlying objects.
    import sip

    if version is not None:
        sip.setapi('QString', version)
        sip.setapi('QVariant', version)

    from PyQt4 import QtGui, QtCore, QtSvg

    if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
        raise ImportError("QtConsole requires PyQt4 >= 4.7, found %s" %
                          QtCore.PYQT_VERSION_STR)

    # Alias PyQt-specific functions for PySide compatibility.
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot

    # query for the API version (in case version == None)
    version = sip.getapi('QString')
    api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
    return QtCore, QtGui, QtSvg, api 
Example 19
Project: pySINDy   Author: luckystarufo   File: qt_loaders.py    License: MIT License 5 votes vote down vote up
def import_pyqt5():
    """
    Import PyQt5

    ImportErrors rasied within this function are non-recoverable
    """

    from PyQt5 import QtCore, QtSvg, QtWidgets, QtGui, QtPrintSupport

    import sip

    # Alias PyQt-specific functions for PySide compatibility.
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot

    # Join QtGui and QtWidgets for Qt4 compatibility.
    QtGuiCompat = types.ModuleType('QtGuiCompat')
    QtGuiCompat.__dict__.update(QtGui.__dict__)
    QtGuiCompat.__dict__.update(QtWidgets.__dict__)
    QtGuiCompat.__dict__.update(QtPrintSupport.__dict__)

    api = QT_API_PYQT5
    return QtCore, QtGuiCompat, QtSvg, api 
Example 20
Project: orstools-qgis-plugin   Author: GIScience   File: maptools.py    License: MIT License 5 votes vote down vote up
def deactivate(self):
        super(LineTool, self).deactivate()
        self.deactivated.emit()


# class PointTool(QgsMapToolEmitPoint):
#     """Point Map tool to capture mapped coordinates."""
#
#     def __init__(self, canvas, button):
#         """
#         :param canvas: current map canvas
#         :type: QgsMapCanvas
#
#         :param button: name of 'Map!' button pressed.
#         :type button: str
#         """
#
#         QgsMapToolEmitPoint.__init__(self, canvas)
#         self.canvas = canvas
#         self.button = button
#         self.cursor = QCursor(QPixmap(RESOURCE_PREFIX + 'icon_locate.png').scaledToWidth(48), 24, 24)
#
#     canvasClicked = pyqtSignal(['QgsPointXY', 'QString'])
#     def canvasReleaseEvent(self, event):
#         #Get the click and emit a transformed point
#
#         crsSrc = self.canvas.mapSettings().destinationCrs()
#
#         point_oldcrs = event.mapPoint()
#
#         xform = transform.transformToWGS(crsSrc)
#         point_newcrs = xform.transform(point_oldcrs)
#
#         QApplication.restoreOverrideCursor()
#
#         self.canvasClicked.emit(point_newcrs, self.button)
#
#     def activate(self):
#         QApplication.setOverrideCursor(self.cursor) 
Example 21
Project: pyblish-maya   Author: pyblish   File: Qt.py    License: GNU Lesser General Public License v3.0 5 votes vote down vote up
def _pyqt5():
    import PyQt5.Qt
    from PyQt5 import QtCore, QtWidgets, uic

    _remap(QtCore, "Signal", QtCore.pyqtSignal)
    _remap(QtCore, "Slot", QtCore.pyqtSlot)
    _remap(QtCore, "Property", QtCore.pyqtProperty)

    _add(QtCompat, "__binding__", PyQt5.__name__)
    _add(QtCompat, "__binding_version__", PyQt5.QtCore.PYQT_VERSION_STR)
    _add(QtCompat, "__qt_version__", PyQt5.QtCore.QT_VERSION_STR)
    _add(QtCompat, "load_ui", lambda fname: uic.loadUi(fname))
    _add(QtCompat, "translate", QtCore.QCoreApplication.translate)
    _add(QtCompat, "setSectionResizeMode",
         QtWidgets.QHeaderView.setSectionResizeMode)

    _maintain_backwards_compatibility(PyQt5)

    return PyQt5 
Example 22
Project: CNCGToolKit   Author: cineuse   File: Qt.py    License: MIT License 5 votes vote down vote up
def _pyqt5():
    import PyQt5.Qt
    from PyQt5 import QtCore, QtWidgets, uic

    _remap(QtCore, "Signal", QtCore.pyqtSignal)
    _remap(QtCore, "Slot", QtCore.pyqtSlot)
    _remap(QtCore, "Property", QtCore.pyqtProperty)

    _add(PyQt5, "__binding__", PyQt5.__name__)
    _add(PyQt5, "load_ui", lambda fname: uic.loadUi(fname))
    _add(PyQt5, "translate", lambda context, sourceText, disambiguation, n: (
        QtCore.QCoreApplication(context, sourceText,
                                disambiguation, n)))
    _add(PyQt5,
         "setSectionResizeMode",
         QtWidgets.QHeaderView.setSectionResizeMode)

    _maintain_backwards_compatibility(PyQt5)

    return PyQt5 
Example 23
Project: MAIAN   Author: ivicanikolicsg   File: gui-maian.py    License: MIT License 5 votes vote down vote up
def __init__(self, myvar, parent=None):
        QtCore.QThread.__init__(self, parent)
        self.notifyProgress = QtCore.pyqtSignal(int)
        self.l = myvar 
Example 24
Project: mu   Author: mu-editor   File: test_logic.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_handle_open_file():
    """
    Ensure on_open_file event handler fires as expected with the editor's
    direct_load when the view's open_file signal is emitted.
    """

    class Dummy(QObject):
        open_file = pyqtSignal(str)

    view = Dummy()
    edit = mu.logic.Editor(view)
    m = mock.MagicMock()
    edit.direct_load = m
    view.open_file.emit("/test/path.py")
    m.assert_called_once_with("/test/path.py") 
Example 25
Project: Carnets   Author: holzschu   File: qt_loaders.py    License: BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
def import_pyqt4(version=2):
    """
    Import PyQt4

    Parameters
    ----------
    version : 1, 2, or None
      Which QString/QVariant API to use. Set to None to use the system
      default

    ImportErrors rasied within this function are non-recoverable
    """
    # The new-style string API (version=2) automatically
    # converts QStrings to Unicode Python strings. Also, automatically unpacks
    # QVariants to their underlying objects.
    import sip

    if version is not None:
        sip.setapi('QString', version)
        sip.setapi('QVariant', version)

    from PyQt4 import QtGui, QtCore, QtSvg

    if not check_version(QtCore.PYQT_VERSION_STR, '4.7'):
        raise ImportError("QtConsole requires PyQt4 >= 4.7, found %s" %
                          QtCore.PYQT_VERSION_STR)

    # Alias PyQt-specific functions for PySide compatibility.
    QtCore.Signal = QtCore.pyqtSignal
    QtCore.Slot = QtCore.pyqtSlot

    # query for the API version (in case version == None)
    version = sip.getapi('QString')
    api = QT_API_PYQTv1 if version == 1 else QT_API_PYQT
    return QtCore, QtGui, QtSvg, api 
Example 26
Project: qutebrowser   Author: qutebrowser   File: debug.py    License: GNU General Public License v3.0 4 votes vote down vote up
def log_signals(obj: QObject) -> QObject:
    """Log all signals of an object or class.

    Can be used as class decorator.
    """
    def log_slot(obj: QObject, signal: pyqtSignal, *args: typing.Any) -> None:
        """Slot connected to a signal to log it."""
        dbg = dbg_signal(signal, args)
        try:
            r = repr(obj)
        except RuntimeError:  # pragma: no cover
            r = '<deleted>'
        log.signals.debug("Signal in {}: {}".format(r, dbg))

    def connect_log_slot(obj: QObject) -> None:
        """Helper function to connect all signals to a logging slot."""
        metaobj = obj.metaObject()
        for i in range(metaobj.methodCount()):
            meta_method = metaobj.method(i)
            qtutils.ensure_valid(meta_method)
            if meta_method.methodType() == QMetaMethod.Signal:
                name = meta_method.name().data().decode('ascii')
                if name != 'destroyed':
                    signal = getattr(obj, name)
                    try:
                        signal.connect(functools.partial(
                            log_slot, obj, signal))
                    except TypeError:  # pragma: no cover
                        pass

    if inspect.isclass(obj):
        old_init = obj.__init__  # type: ignore[misc]

        @functools.wraps(old_init)
        def new_init(self: typing.Any,
                     *args: typing.Any,
                     **kwargs: typing.Any) -> None:
            """Wrapper for __init__() which logs signals."""
            old_init(self, *args, **kwargs)
            connect_log_slot(self)

        obj.__init__ = new_init  # type: ignore[misc]
    else:
        connect_log_slot(obj)

    return obj 
Example 27
Project: qutebrowser   Author: qutebrowser   File: debug.py    License: GNU General Public License v3.0 4 votes vote down vote up
def signal_name(sig: pyqtSignal) -> str:
    """Get a cleaned up name of a signal.

    Unfortunately, the way to get the name of a signal differs based on:
    - PyQt versions (5.11 added .signatures for unbound signals)
    - Bound vs. unbound signals

    Here, we try to get the name from .signal or .signatures, or if all else
    fails, extract it from the repr().

    Args:
        sig: The pyqtSignal

    Return:
        The cleaned up signal name.
    """
    if hasattr(sig, 'signal'):
        # Bound signal
        # Examples:
        # sig.signal == '2signal1'
        # sig.signal == '2signal2(QString,QString)'
        m = re.fullmatch(r'[0-9]+(?P<name>.*)\(.*\)',
                         sig.signal)  # type: ignore[attr-defined]
    elif hasattr(sig, 'signatures'):
        # Unbound signal, PyQt >= 5.11
        # Examples:
        # sig.signatures == ('signal1()',)
        # sig.signatures == ('signal2(QString,QString)',)
        m = re.fullmatch(r'(?P<name>.*)\(.*\)',
                         sig.signatures[0])  # type: ignore[attr-defined]
    else:  # pragma: no cover
        # Unbound signal, PyQt < 5.11
        # Examples:
        # repr(sig) == "<unbound PYQT_SIGNAL SignalObject.signal1[]>"
        # repr(sig) == "<unbound PYQT_SIGNAL SignalObject.signal2[str, str]>"
        # repr(sig) == "<unbound PYQT_SIGNAL timeout()>"
        # repr(sig) == "<unbound PYQT_SIGNAL valueChanged(int)>"
        patterns = [
            r'<unbound PYQT_SIGNAL [^.]*\.(?P<name>[^[]*)\[.*>',
            r'<unbound PYQT_SIGNAL (?P<name>[^(]*)\(.*>',
        ]
        for pattern in patterns:
            m = re.fullmatch(pattern, repr(sig))
            if m is not None:
                break

    assert m is not None, sig
    return m.group('name') 
Example 28
Project: pipeline   Author: liorbenhorin   File: Qt.py    License: MIT License 4 votes vote down vote up
def _pyqt4():
    # Attempt to set sip API v2 (must be done prior to importing PyQt4)
    import sip
    try:
        sip.setapi("QString", 2)
        sip.setapi("QVariant", 2)
        sip.setapi("QDate", 2)
        sip.setapi("QDateTime", 2)
        sip.setapi("QTextStream", 2)
        sip.setapi("QTime", 2)
        sip.setapi("QUrl", 2)
    except AttributeError:
        raise ImportError
        # PyQt4 < v4.6
    except ValueError:
        # API version already set to v1
        raise ImportError

    import PyQt4.Qt
    from PyQt4 import QtCore, QtGui, uic

    _remap(PyQt4, "QtWidgets", QtGui)
    _remap(QtCore, "Signal", QtCore.pyqtSignal)
    _remap(QtCore, "Slot", QtCore.pyqtSlot)
    _remap(QtCore, "Property", QtCore.pyqtProperty)
    _remap(QtCore, "QItemSelection", QtGui.QItemSelection)
    _remap(QtCore, "QStringListModel", QtGui.QStringListModel)
    _remap(QtCore, "QItemSelectionModel", QtGui.QItemSelectionModel)
    _remap(QtCore, "QSortFilterProxyModel", QtGui.QSortFilterProxyModel)
    _remap(QtCore, "QAbstractProxyModel", QtGui.QAbstractProxyModel)

    try:
        from PyQt4 import QtWebKit
        _remap(PyQt4, "QtWebKitWidgets", QtWebKit)
    except ImportError:
        # QtWebkit is optional in Qt , therefore might not be available
        pass

    _add(PyQt4, "QtCompat", self)
    _add(PyQt4, "__binding__", PyQt4.__name__)
    _add(PyQt4, "load_ui", lambda fname: uic.loadUi(fname))
    _add(PyQt4, "translate", lambda context, sourceText, disambiguation, n: (
        QtCore.QCoreApplication(context, sourceText,
                                disambiguation, None, n)))
    _add(PyQt4, "setSectionResizeMode", QtGui.QHeaderView.setResizeMode)

    _maintain_backwards_compatibility(PyQt4)

    return PyQt4 
Example 29
Project: Mastering-Elasticsearch-7.0   Author: PacktPublishing   File: qt_compat.py    License: MIT License 4 votes vote down vote up
def _setup_pyqt4():
    global QtCore, QtGui, QtWidgets, __version__, is_pyqt5, _getSaveFileName

    def _setup_pyqt4_internal(api):
        global QtCore, QtGui, QtWidgets, \
            __version__, is_pyqt5, _getSaveFileName
        # List of incompatible APIs:
        # http://pyqt.sourceforge.net/Docs/PyQt4/incompatible_apis.html
        _sip_apis = ["QDate", "QDateTime", "QString", "QTextStream", "QTime",
                     "QUrl", "QVariant"]
        try:
            import sip
        except ImportError:
            pass
        else:
            for _sip_api in _sip_apis:
                try:
                    sip.setapi(_sip_api, api)
                except ValueError:
                    pass
        from PyQt4 import QtCore, QtGui
        __version__ = QtCore.PYQT_VERSION_STR
        # PyQt 4.6 introduced getSaveFileNameAndFilter:
        # https://riverbankcomputing.com/news/pyqt-46
        if __version__ < LooseVersion("4.6"):
            raise ImportError("PyQt<4.6 is not supported")
        QtCore.Signal = QtCore.pyqtSignal
        QtCore.Slot = QtCore.pyqtSlot
        QtCore.Property = QtCore.pyqtProperty
        _getSaveFileName = QtGui.QFileDialog.getSaveFileNameAndFilter

    if QT_API == QT_API_PYQTv2:
        _setup_pyqt4_internal(api=2)
    elif QT_API == QT_API_PYSIDE:
        from PySide import QtCore, QtGui, __version__, __version_info__
        # PySide 1.0.3 fixed the following:
        # https://srinikom.github.io/pyside-bz-archive/809.html
        if __version_info__ < (1, 0, 3):
            raise ImportError("PySide<1.0.3 is not supported")
        _getSaveFileName = QtGui.QFileDialog.getSaveFileName
    elif QT_API == QT_API_PYQT:
        _setup_pyqt4_internal(api=1)
    else:
        raise ValueError("Unexpected value for the 'backend.qt4' rcparam")
    QtWidgets = QtGui

    def is_pyqt5():
        return False 
Example 30
Project: imperialism-remake   Author: Trilarion   File: qt.py    License: GNU General Public License v3.0 4 votes vote down vote up
def make_widget_draggable(parent):
    """
    Takes any QtWidgets.QWidget derived class and emits a signal on mouseMoveEvent emitting the position change since
    the last mousePressEvent. By default mouseMoveEvents are only invoked while the mouse is pressed. Therefore
    we can use it to listen to dragging or implement dragging.
    """

    # noinspection PyPep8Naming
    class DraggableWidgetSubclass(parent):
        """
        Draggable widget.
        """

        #: signal
        dragged = QtCore.pyqtSignal(QtCore.QPoint)

        def __init__(self, *args, **kwargs):
            super().__init__(*args, **kwargs)
            self.position_on_click = None

        def mousePressEvent(self, event):  # noqa: N802
            """
            The mouse is now pressed. Store initial position on screen.

            :param event:
            """
            self.position_on_click = event.globalPos()
            super().mousePressEvent(event)

        def mouseMoveEvent(self, event):  # noqa: N802
            """
            The mouse has moved. Calculate difference to previous position and emit signal dragged. Update position.

            Note: This slot is only called if the mouse is also pressed (see documentation).

            :param event:
            """
            super().mouseMoveEvent(event)
            position_now = event.globalPos()
            self.dragged.emit(position_now - self.position_on_click)
            self.position_on_click = position_now

    return DraggableWidgetSubclass