Python PyQt5.QtCore.pyqtSignal() Examples

The following are 30 code examples of PyQt5.QtCore.pyqtSignal(). 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: qt_compat.py    From twitter-stock-recommendation with MIT License 32 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 #2
Source File: qt.py    From imperialism-remake with GNU General Public License v3.0 9 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 #3
Source File: InstanceContainer.py    From Uranium with 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 #4
Source File: qt_loaders.py    From Carnets with 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 #5
Source File: find_toolbar.py    From pandasgui with 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 #6
Source File: maptools.py    From orstools-qgis-plugin with 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 #7
Source File: qt_loaders.py    From pySINDy with 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 #8
Source File: qt_loaders.py    From pySINDy with 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 #9
Source File: Qt.py    From uExport with zlib 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 #10
Source File: config.py    From kite with 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 #11
Source File: gui-maian.py    From MAIAN with 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 #12
Source File: test_logic.py    From mu with 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 #13
Source File: qt_loaders.py    From PyDev.Debugger with 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 #14
Source File: qt_loaders.py    From PyDev.Debugger with 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 #15
Source File: qt_loaders.py    From Carnets with 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 #16
Source File: debug.py    From qutebrowser with 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 #17
Source File: message.py    From qutebrowser with GNU General Public License v3.0 5 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 #18
Source File: analysis.py    From rteeg with MIT License 4 votes vote down vote up
def _loop_worker(stream, func, args, buffer_len, kill_signal, show_window=False,
                 pyqt_signal=None):
    """Call `func(*args)` each time `stream._eeg_data` increases by
    `buffer_len`.

    Parameters
    ----------
    stream : rteeg.EEGStream
        Stream of EEG data or event markers.
    func : function
        The function to be called everytime the length of the buffer reaches
        `buffer_len`.
    args : tuple
        Arguments to pass to `func`.
    buffer_len : int, float
        The duration of the buffer in seconds.
    kill_signal
        If `show_window` is False, `kill_signal` must be threading.Event. If
        `show_window` is True, `kill_signal` must be QThread method.
    show_window : bool
        Whether or not PyQt window is shown. If True, will emit `pyqt_signal`
        to refresh PyQt window.
    pyqt_signal : pyqt.QtCore.pyqtSignal
        Signal which, when emitted, will change text on the PyQt window.
    """
    sleep_time = 0.001  # Time to sleep between buffer_len queries.
    t_zero = local_clock()

    if show_window:
        while not kill_signal:
            t_one = stream.data[-1][-1]
            if t_one - t_zero >= buffer_len:
                t_zero = t_one
                # Refresh PyQt window with the str that `func` returns.
                pyqt_signal.emit(func(*args))
            time.sleep(sleep_time)
    else:
        while not kill_signal.is_set():
            t_one = stream.data[-1][-1]
            if t_one - t_zero >= buffer_len:
                t_zero = t_one
                func(*args)
            time.sleep(sleep_time) 
Example #19
Source File: Qt.py    From CNCGToolKit with MIT License 4 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 #20
Source File: Qt.py    From pyblish-maya with GNU Lesser General Public License v3.0 4 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 #21
Source File: peakonly.py    From peakonly with MIT License 4 votes vote down vote up
def _download(mode, progress_callback):
        """
        Download necessary data
        Parameters
        ----------
        mode : str
            one of three ('models', 'data', 'example')
        progress_callback : QtCore.pyqtSignal
            indicating progress in %
        """
        if mode == 'models':
            folder = 'data/weights'
            if not os.path.exists(folder):
                os.mkdir(folder)
            # Classifier
            url = 'https://getfile.dokpub.com/yandex/get/https://yadi.sk/d/rAhl2u7WeIUGYA'
            file = os.path.join(folder, 'Classifier.pt')
            urllib.request.urlretrieve(url, file, progress_callback.emit)
            # Segmentator
            url = 'https://getfile.dokpub.com/yandex/get/https://yadi.sk/d/9m5e3C0q0HKbuw'
            file = os.path.join(folder, 'Segmentator.pt')
            urllib.request.urlretrieve(url, file, progress_callback.emit)
            # RecurrentCNN
            url = 'https://getfile.dokpub.com/yandex/get/https://yadi.sk/d/1IrXRWDWhANqKw'
            file = os.path.join(folder, 'RecurrentCNN.pt')
            urllib.request.urlretrieve(url, file, progress_callback.emit)
        elif mode == 'data':
            folder = 'data/annotation'
            if not os.path.exists(folder):
                os.mkdir(folder)
            url = 'https://getfile.dokpub.com/yandex/get/https://yadi.sk/d/f6BiwqWYF4UVnA'
            file = 'data/annotation/annotation.zip'
            urllib.request.urlretrieve(url, file, progress_callback.emit)
            with zipfile.ZipFile(file) as zip_file:
                zip_file.extractall(folder)
            os.remove(file)
        elif mode == 'example':
            url = 'https://getfile.dokpub.com/yandex/get/https://yadi.sk/d/BhQNge3db7M2Lw'
            file = 'data/mix.mzML'
            urllib.request.urlretrieve(url, file, progress_callback.emit)
        else:
            assert False, mode 
Example #22
Source File: debug.py    From qutebrowser with 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 #23
Source File: qt_compat.py    From python3_ios with BSD 3-Clause "New" or "Revised" License 4 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 #24
Source File: debug.py    From qutebrowser with 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 #25
Source File: Qt.py    From pipeline with MIT License 4 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 #26
Source File: qt.py    From imperialism-remake with GNU General Public License v3.0 4 votes vote down vote up
def make_GraphicsItem_draggable(parent):
    """
    Takes a QtWidgets.QGraphicsItem and adds signals for dragging the object around. For this the item must have the
    ItemIsMovable and ItemSendsScenePositionChanges flags set. Only use it when really needed because there is
    some performance hit attached.
    """

    # noinspection PyPep8Naming
    class DraggableGraphicsItem(parent, QtCore.QObject):
        """
        Draggable GraphicsItem.
        """
        changed = QtCore.pyqtSignal(object)

        def __init__(self, *args, **kwargs):
            """
            By default QGraphicsItems are not movable and also do not emit signals when the position is changed for
            performance reasons. We need to turn this on.
            """
            parent.__init__(self, *args, **kwargs)
            self.parent = parent
            QtCore.QObject.__init__(self)

            self.setFlags(QtWidgets.QGraphicsItem.ItemIsMovable
                          | QtWidgets.QGraphicsItem.ItemSendsScenePositionChanges)

        def itemChange(self, change, value):  # noqa: N802
            """
            Catch all item position changes and emit the changed signal with the value (which will be the position).

            :param change:
            :param value:
            """
            if change == QtWidgets.QGraphicsItem.ItemPositionChange:
                self.changed.emit(value)

            return parent.itemChange(self, change, value)

    return DraggableGraphicsItem


# Some classes we need (just to make the naming clear), Name will be used in Stylesheet selectors

#: QToolBar made draggable 
Example #27
Source File: qt.py    From imperialism-remake with 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 
Example #28
Source File: videoslider.py    From vidcutter with GNU General Public License v3.0 4 votes vote down vote up
def initThumbs(self) -> None:
        framesize = self.parent.videoService.framesize()
        thumbsize = QSize(
            VideoService.config.thumbnails['TIMELINE'].height() * (framesize.width() / framesize.height()),
            VideoService.config.thumbnails['TIMELINE'].height())
        positions, frametimes = [], []
        thumbs = int(math.ceil((self.rect().width() - (self.offset * 2)) / thumbsize.width()))
        for pos in range(thumbs):
            val = QStyle.sliderValueFromPosition(self.minimum(), self.maximum(),
                                                 (thumbsize.width() * pos) - self.offset,
                                                 self.rect().width() - (self.offset * 2))
            positions.append(val)
        positions[0] = 1000
        [frametimes.append(self.parent.delta2QTime(msec).toString(self.parent.timeformat)) for msec in positions]

        class ThumbWorker(QObject):
            completed = pyqtSignal(list)

            def __init__(self, settings: QSettings, media: str, times: list, size: QSize):
                super(ThumbWorker, self).__init__()
                self.settings = settings
                self.media = media
                self.times = times
                self.size = size

            @pyqtSlot()
            def generate(self):
                frames = list()
                [
                    frames.append(VideoService.captureFrame(self.settings, self.media, frame, self.size))
                    for frame in self.times
                ]
                self.completed.emit(frames)

        self.thumbsThread = QThread(self)
        self.thumbsWorker = ThumbWorker(self.parent.settings, self.parent.currentMedia, frametimes, thumbsize)
        self.thumbsWorker.moveToThread(self.thumbsThread)
        self.thumbsThread.started.connect(self.parent.sliderWidget.setLoader)
        self.thumbsThread.started.connect(self.thumbsWorker.generate)
        self.thumbsThread.finished.connect(self.thumbsThread.deleteLater, Qt.DirectConnection)
        self.thumbsWorker.completed.connect(self.buildTimeline)
        self.thumbsWorker.completed.connect(self.thumbsWorker.deleteLater, Qt.DirectConnection)
        self.thumbsWorker.completed.connect(self.thumbsThread.quit, Qt.DirectConnection)
        self.thumbsThread.start() 
Example #29
Source File: Qt.py    From uExport with zlib License 3 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 #30
Source File: Qt.py    From pyblish-maya with GNU Lesser General Public License v3.0 3 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"

    _add(QtCompat, "__binding__", PyQt4.__name__)
    _add(QtCompat, "__binding_version__", PyQt4.QtCore.PYQT_VERSION_STR)
    _add(QtCompat, "__qt_version__", PyQt4.QtCore.QT_VERSION_STR)
    _add(QtCompat, "load_ui", lambda fname: uic.loadUi(fname))
    _add(QtCompat, "setSectionResizeMode", QtGui.QHeaderView.setResizeMode)

    # PySide2 differs from Qt4 in that Qt4 has one extra argument
    # which is always `None`. The lambda arguments represents the PySide2
    # interface, whereas the arguments passed to `.translate` represent
    # those expected of a Qt4 binding.
    _add(QtCompat, "translate",
         lambda context, sourceText, disambiguation, n:
         QtCore.QCoreApplication.translate(context,
                                           sourceText,
                                           disambiguation,
                                           QtCore.QCoreApplication.CodecForTr,
                                           n))

    _maintain_backwards_compatibility(PyQt4)

    return PyQt4