Exemplo n.º 1
0
    def keyPressEvent(self, event):
        current_frame = self.player.preview_thread.current_frame
        key_value = event.key()
        print(key_value)

        modifiers = int(event.modifiers())
        if (key_value > 0 and key_value != Qt.Key_Shift
                and key_value != Qt.Key_Alt and key_value != Qt.Key_Control
                and key_value != Qt.Key_Meta):
            # A valid keysequence was detected
            key = QKeySequence(modifiers + key_value)
        else:
            # No valid keysequence detected
            return

        # Debug
        log.info("keyPressEvent: %s" % (key.toString()))

        color = self.getColorByName("actionCut+" + key.toString())
        print("actionCut+" + key.toString(), color)
        if color:
            self.timelineWidget.cut(key.toString(), current_frame, color)
        elif key.matches(self.getShortcutByName(
                "actionAddTrack")) == QKeySequence.ExactMatch:
            self.timelineWidget.addTrack("track_test")
Exemplo n.º 2
0
        def _bind(self, seq, cmd):
            ''' Binds a hotkey to a command name.

			seq can either be a QKeySequence or a string parseable by QKeySequence
			eg "ctrl+shift+k" '''
            try:
                seq = QKeySequence(seq)
            except:
                pass

            t = seqToTuple(seq)
            log.debug('Binding hotkey "{hotkey}" => "{command}"',
                      hotkey=seq.toString(),
                      command=cmd)

            try:
                self.hk.register(t, cmd)
            except SystemRegisterError:
                log.exception('Failed to bind hotkey "{hotkey}"',
                              hotkey=seq.toString())
            else:
                return True
            #endtry

            return False
Exemplo n.º 3
0
        def add(self, seq, command):
            ''' Add a new hotkey with with a command name intended to be saved to the config '''
            try:
                seq = QKeySequence(seq)
            except:
                pass

            seq = seq.toString(
            )  # TODO: Removed this (use kyseq directly). UPDATE LOGS when you do (toString)

            hks = config.default.get('hotkeys', {})
            if seq in hks:
                log.warning('Reassigning existing sequence "{hotkey}"',
                            hotkey=seq)
            #endif

            hks[seq] = command
            config.default.set('hotkeys', hks)
            config.default.save()  # TODO: Move this to settings UI?

            log.debug('Attempting to bind "{sequence}"', sequence=seq)

            if command not in self.commands:
                log.warning(
                    'Saved hotkey "{hotkey}" to unknown command "{command}"',
                    hotkey=seq,
                    command=command)
            #endif

            return True
Exemplo n.º 4
0
        def hasHotkey(self, seq):
            try:
                seq = QKeySequence(seq)
            except:
                pass

            return seq.toString() in config.default.get('hotkeys', {})
Exemplo n.º 5
0
    def setShortcut(self, shortcut: QtGui.QKeySequence):
        action = None
        try:
            for action in self.actions_list:
                if (action.shortcut
                        == shortcut) and (self is not action) and not (
                            shortcut == QtGui.QKeySequence('')):
                    raise ValueError(
                        'Shortcut is already in use by "{}"\n'.format(
                            action.text))
            else:  # the shortcut is free
                self.lineEdit.setStyleSheet(self.regularLineEditStyleSheet)
                self.lineEdit.setKeySequence(shortcut)
                self.dataBase.update_shortcut(self.text, shortcut.toString())
                self.shortcut = shortcut
        except ValueError as e:
            self.lineEdit.clearText()
            reply = QtWidgets.QMessageBox.question(
                self.parent, "Shortcut in use",
                str(e) + "What would you like to do?",
                QtWidgets.QMessageBox.Retry | QtWidgets.QMessageBox.Ignore
                | QtWidgets.QMessageBox.Cancel)

            if reply == QtWidgets.QMessageBox.Retry:
                self.tableWidget.parent().activateWindow()
                self.lineEdit.setFocus()
                self.lineEdit.setStyleSheet(self.errorLineEditStyleSheet)
            elif reply == QtWidgets.QMessageBox.Cancel:
                self.lineEdit.clearFocus()
            else:  # Ignore - solve the collision
                action.setShortcut(QtGui.QKeySequence(''))
                self.setShortcut(shortcut)
Exemplo n.º 6
0
    def change_keyseq(self, group, name, old_keyseq, keyseq):
        """
        Customize a shortcut's activating key sequence.
        """
        if old_keyseq:
            old_keyseq = QKeySequence(old_keyseq)
            old_keytext = str(old_keyseq.toString())
            self._keyseq_target_actions[old_keytext].remove((group, name))
        try:
            keyseq = QKeySequence(keyseq)
            keytext = str(keyseq.toString())
            target_name_set = self._keyseq_target_actions[keytext]
        except KeyError:
            target_name_set = self._keyseq_target_actions[keytext] = set()
            self._add_global_shortcut_listener(keyseq)

        target_name_set.add((group, name))
        self._update_tooltip(group, name, keyseq)
Exemplo n.º 7
0
    def change_keyseq(self, group, name, old_keyseq, keyseq):
        """
        Customize a shortcut's activating key sequence.
        """
        if old_keyseq:
            old_keyseq = QKeySequence(old_keyseq)
            old_keytext = str(old_keyseq.toString())
            self._keyseq_target_actions[old_keytext].remove((group, name))
        try:
            keyseq = QKeySequence(keyseq)
            keytext = str(keyseq.toString())
            target_name_set = self._keyseq_target_actions[keytext]
        except KeyError:
            target_name_set = self._keyseq_target_actions[keytext] = set()
            self._add_global_shortcut_listener(keyseq)

        target_name_set.add((group, name))
        self._update_tooltip(group, name, keyseq)
Exemplo n.º 8
0
    def add_shortcut(self, scope: qw.QWidget, shortcut: str) -> None:
        """ Adds shortcut and tooltip. """
        keys = QKeySequence(shortcut, QKeySequence.PortableText)

        self.scoped_shortcut = qw.QShortcut(keys, scope)
        self.scoped_shortcut.setContext(Qt.WidgetWithChildrenShortcut)
        self.scoped_shortcut.activated.connect(self.click)

        self.setToolTip(keys.toString(QKeySequence.NativeText))
Exemplo n.º 9
0
 def keyPressEvent(self, event):
     try:
         key_sequence = QKeySequence(event.modifiers() | event.key())
         key_sequence_ascii_representation = key_sequence.toString(
         ).encode('ascii', errors='ignore').decode()
         self.setText(key_sequence_ascii_representation)
     except Exception as e:
         # Ignoring unknown errors since we can't do anything about it.
         pass
Exemplo n.º 10
0
 def getQKeySequence(self, key):
     if key.startswith('0x'):
         try:
             key = int(key, 16)
         except ValueError:
             pass
     seq = QKeySequence(key)
     s = seq.toString()
     if len(s) == 1 and s.isalpha():
         self.ignore_keys.append(ord(s))
     return seq
Exemplo n.º 11
0
 def setShortcut(self, identifier, shortcut: QtGui.QKeySequence):
     """Set a shortcut for the action named `identifier`."""
     action = self.actions[identifier]
     action.shortcut = shortcut
     if action.shortcut == action.defaultShortcut:
         # remove from storage, if it's there (we only store non-defaults)
         if identifier in config.storage.gui.shortcuts:
             del config.storage.gui.shortcuts[identifier]
     else:
         config.storage.gui.shortcuts[identifier] = shortcut.toString()
     self.shortcutChanged.emit(identifier, shortcut)
Exemplo n.º 12
0
 def test_load_default_shortcuts(self):
     shorts_count = self.shortcuts_manager.result_widget.topLevelItemCount()
     item = self.shortcuts_manager.result_widget.topLevelItem(0)
     shortcut_keys = item.text(1)
     # Expected data
     expected_key = QKeySequence(Qt.CTRL + Qt.Key_N)
     expected_key_str = expected_key.toString(QKeySequence.NativeText)
     # Just one shortcut should be loaded
     self.assertEqual(shorts_count, 1)
     # The key should be the same as the expected
     self.assertEqual(shortcut_keys, expected_key_str)
Exemplo n.º 13
0
 def setShortcut(self, identifier, shortcut: QtGui.QKeySequence):
     """Set a shortcut for the action named `identifier`."""
     action = self.actions[identifier]
     action.shortcut = shortcut
     if action.shortcut == action.defaultShortcut:
         # remove from storage, if it's there (we only store non-defaults)
         if identifier in config.storage.gui.shortcuts:
             del config.storage.gui.shortcuts[identifier]
     else:
         config.storage.gui.shortcuts[identifier] = shortcut.toString()
     self.shortcutChanged.emit(identifier, shortcut)
Exemplo n.º 14
0
    def on_new_shortcut(self):
        new_shortcut = str(QKeySequence.toString(self.new_shortcut.keySequence()))
        self.controller.update_hotkey(self.selected_option, new_shortcut)

        # Regenerate list
        self.ui.listWidget_hotkey.clear()
        self.generate_hotkey_list()

        # Update inputs
        self.ui.lineEdit_current_shortcut.setText(new_shortcut)
        self.new_shortcut.clear()
Exemplo n.º 15
0
    def on_new_shortcut(self):
        _new_shortcut = str(QKeySequence.toString(self.new_shortcut.keySequence()))
        self.controller.update_hotkey(self.selected_option, _new_shortcut)

        # Regenerate list
        self.ui.listWidget.clear()
        self.generate_hotkey_list()

        # Update inputs
        self.ui.input_cur_shortcut.setText(_new_shortcut) # possible self.model.get('Hotkeys', self.selected_option)
        self.new_shortcut.clear()
Exemplo n.º 16
0
        def _unbind(self, seq, quiet=False):
            ''' Removes a hotkey binding. If Quiet is true, will not warn if the binding doesn't exist '''
            try:
                seq = QKeySequence(seq)
            except:
                pass

            t = seqToTuple(seq)
            log.debug('Unbinding hotkey "{hotkey}"', hotkey=seq.toString())

            try:
                self.hk.unregister(t)
            except UnregisterError:
                if not quiet:
                    log.warn('Tried to unbind nonexistent hotkey "{hotkey}"',
                             hotkey=seq.toString())
            else:
                return True
            #endtry

            return False
Exemplo n.º 17
0
class HotkeyLineEdit(QLineEdit):
    key_sequence = None

    def __init__(self, parent=None):
        super(HotkeyLineEdit, self).__init__(parent)
        self.clearKeySequence()

    def clearKeySequence(self):
        self.key_sequence = QKeySequence()
        self.updateText()

    def setKeySequence(self, keyseq):
        if not isinstance(keyseq, QKeySequence): raise RuntimeError
        self.key_sequence = keyseq
        self.updateText()

    def updateText(self):
        self.setText(self.key_sequence.toString(QKeySequence.NativeText))

    def mousePressEvent(self, event):
        log.info("Mouse press")
        # TODO: construct a data structure to hold mouse presses that can be used as shortcuts

    def keyPressEvent(self, event):
        log.info("Key Press")
        key = event.key(); 
        key = Qt.Key(key); 

        # Ignore unknown keys
        # and if modifier keys come alone
        if key == Qt.Key_unknown or key in (Qt.Key_Control, Qt.Key_Alt, Qt.Key_AltGr, Qt.Key_Shift):
            return

        # Pressing Backspace will clear the content
        if key == Qt.Key_Backspace:
            self.setText(None)
            self.clearKeySequence()
            return
        
        # Checking for key combinations
        modifiers = event.modifiers();

        if(modifiers & Qt.NoModifier):
            return
        if(modifiers & Qt.ShiftModifier):
            key += Qt.SHIFT
        if(modifiers & Qt.ControlModifier):
            key += Qt.CTRL 
        if(modifiers & Qt.AltModifier):
            key += Qt.ALT 

        self.setKeySequence(QKeySequence(key))
Exemplo n.º 18
0
    def keyPressEvent(self, event):
        """Handler when a key is pressed.

        * use Escape to leave the control
        * use Enter to accept the sequence

        """

        if event.key() == Qt.Key_Escape:
            self.setFocus(False)

        elif event.key() == Qt.Key_Return:
            self._accept()

        elif not event.isAutoRepeat():
            modifiers = 0
            # event.modifiers().testFlag(...)
            if event.modifiers() & Qt.ControlModifier:
                modifiers |= Qt.CTRL
            if event.modifiers() & Qt.ShiftModifier:
                modifiers |= Qt.SHIFT
            if event.modifiers() & Qt.AltModifier:
                modifiers |= Qt.ALT
            if event.modifiers() & Qt.MetaModifier:
                modifiers |= Qt.META

            if Qt.Key_Shift <= event.key() <= Qt.Key_Meta:
                self._logger.info(
                    'Only modifiers were pressed ({} / {} / {} ignoring'.
                    format(event.text(), _key_name(event.key()),
                           QKeySequence(event.key()).toString()))

            else:
                self._pressed_keys.append(event.key() | modifiers)
                self._logger.info(
                    'Adding key {} / {} / {} with modifiers ({}) to pressed keys'
                    .format(
                        event.text(),
                        _key_name(event.key()),
                        QKeySequence(event.key()).toString(),
                        # UnicodeEncodeError: 'utf-8' codec can't encode character '\udc21' in position 188: surrogates not allowed
                        QKeySequence(self._pressed_keys[-1]).toString(),
                    ))

                sequence = QKeySequence(*self._pressed_keys)  # up to 4 keys
                self._set_edited_sequence(sequence.toString())

                if len(self._pressed_keys) == 4:
                    # That was the last key out of four possible keys end it here.
                    self._accept()

        event.accept()
Exemplo n.º 19
0
 def _add_global_shortcut_listener(self, keyseq):
     # Create a shortcut for this new key sequence
     # Note: We associate the shortcut with the ENTIRE WINDOW.
     #       We intercept the shortcut and decide which widget to direct it to.
     #       (We don't rely on Qt to do this for us.)
     # Note: This class assumes that all widgets using shortcuts belong to the SAME main window.
     assert keyseq not in self._global_shortcuts
     keyseq = QKeySequence(keyseq)
     keytext = str(keyseq.toString())
     self._global_shortcuts[keytext] = QShortcut(
         QKeySequence(keyseq),
         getMainWindow(),
         member=partial(self._handle_shortcut_pressed, keytext),
         context=Qt.ApplicationShortcut)
Exemplo n.º 20
0
 def _add_global_shortcut_listener(self, keyseq):
     # Create a shortcut for this new key sequence
     # Note: We associate the shortcut with the ENTIRE WINDOW.
     #       We intercept the shortcut and decide which widget to direct it to.
     #       (We don't rely on Qt to do this for us.)
     # Note: This class assumes that all widgets using shortcuts belong to the SAME main window.
     assert keyseq not in self._global_shortcuts
     keyseq = QKeySequence(keyseq)
     keytext = str(keyseq.toString())
     self._global_shortcuts[keytext] = QShortcut(
         QKeySequence(keyseq),
         getMainWindow(),
         member=partial(self._handle_shortcut_pressed, keytext),
         context=Qt.ApplicationShortcut,
     )
Exemplo n.º 21
0
    def keyPressEvent(self, event):
        if event.key() == Qt.Key_Escape:
            self.setKeyboardShortcut("")
            self.close()
            return

        if event.key() == Qt.Key_Backspace:
            self.setKeyboardShortcut("")
            self._should_be_reset = True
            self.close()
            return

        try:
            key_sequence = QKeySequence(event.modifiers() | event.key())
            key_sequence_ascii_representation = key_sequence.toString().encode(
                'ascii', errors='ignore').decode()
            self.setKeyboardShortcut(key_sequence_ascii_representation)
        except Exception as e:
            # Ignoring unknown errors since we can't do anything about it.
            pass
Exemplo n.º 22
0
    def __create_style_button(self, text, tooltip, keys, font_style):
        def toggled(value):
            self.__font = self.__font.change(font_style, value)
            self.__refresh_example_font()

        shortcut = QKeySequence(keys)
        widget = QPushButton(text)
        widget.setShortcut(shortcut)
        widget.setToolTip("{0} ({1})".format(tooltip, shortcut.toString()))
        font = widget.font()
        if font_style == FontStyle.bold:
            font.setBold(True)
        elif font_style == FontStyle.italic:
            font.setItalic(True)
        elif font_style == FontStyle.underline:
            font.setUnderline(True)
        elif font_style == FontStyle.strike:
            font.setStrikeOut(True)
        widget.setFont(font)
        widget.setCheckable(True)
        widget.toggled.connect(toggled)
        return widget
Exemplo n.º 23
0
    def test_save_shortcuts(self):
        data = []

        def called():
            data.append(True)

        actions = gui.FakeActions()
        setattr(actions, 'update_shortcuts', called)
        self.patch(shortcut_manager.actions, 'Actions', lambda: actions)
        self.shortcuts_manager.result_widget.clear()
        key = QKeySequence(Qt.CTRL + Qt.SHIFT + Qt.Key_N)
        key_str = key.toString(QKeySequence.NativeText)
        tree_data = ["New File", key_str, "New-File"]
        item = QTreeWidgetItem(self.shortcuts_manager.result_widget, tree_data)
        item.setFlags(Qt.ItemIsSelectable | Qt.ItemIsEnabled)
        # Before save there is nothing in QSettings
        self.assertEqual(self.settings.value("New-File", None), None)
        # Save
        self.shortcuts_manager.save()
        # After save there is a value for New-File QSettings
        self.assertEqual(self.settings.values["New-File"], key_str)
        # After save check if NINJA call the update_shortcuts in actios.Actions
        self.assertEqual(data, [True])
Exemplo n.º 24
0
class QtKeySequenceEdit(QWidget):
    keySequenceChangedSignal = pyqtSignal(QKeySequence)
    def __init__(self,parent=None):
        super(QtKeySequenceEdit, self).__init__(parent)

        self.m_keySequence = QKeySequence()
        self.m_num = 0
        self.m_lineEdit = QLineEdit(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.m_lineEdit)
        layout.setContentsMargins(0, 0, 0, 0)
        self.m_lineEdit.installEventFilter(self)
        self.m_lineEdit.setReadOnly(True)
        self.m_lineEdit.setFocusProxy(self)
        self.setFocusPolicy(self.m_lineEdit.focusPolicy())
        self.setAttribute(Qt.WA_InputMethodEnabled)

    def eventFilter(self, o, e):
        if o == self.m_lineEdit and e.type() == QEvent.ContextMenu:
            c = e
            menu = self.m_lineEdit.createStandardContextMenu()
            actions = menu.actions()
            for action in actions:
                action.setShortcut(QKeySequence())
                actionString = action.text()
                pos = actionString.rfind('\t')
                if (pos > 0):
                    actionString = actionString[:pos]
                action.setText(actionString)

            actionBefore = None
            if (len(actions) > 0):
                actionBefore = actions[0]
            clearAction = QAction(self.tr("Clear Shortcut"), menu)
            menu.insertAction(actionBefore, clearAction)
            menu.insertSeparator(actionBefore)
            clearAction.setEnabled(not len(self.m_keySequence)<=0)
            clearAction.triggered.connect(self.slotClearShortcut)
            menu.exec(c.globalPos())
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).eventFilter(o, e)

    def slotClearShortcut(self):
        if len(self.m_keySequence) <= 0:
            return
        self.setKeySequence(QKeySequence())
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def handleKeyEvent(self, e):
        nextKey = e.key()
        if (nextKey == Qt.Key_Control or nextKey == Qt.Key_Shift or
                nextKey == Qt.Key_Meta or nextKey == Qt.Key_Alt or
                nextKey == Qt.Key_Super_L or nextKey == Qt.Key_AltGr):
            return

        nextKey |= self.translateModifiers(e.modifiers(), e.text())
        k0 = 0
        k1 = 0
        k2 = 0
        k3 = 0
        l = len(self.m_keySequence)
        if l==1:
            k0 = self.m_keySequence[0]
        elif l==2:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
        elif l==3:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
        elif l==4:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
            k3 = self.m_keySequence[3]
        if self.m_num==0:
            k0 = nextKey
            k1 = 0
            k2 = 0
            k3 = 0
        elif self.m_num==1:
            k1 = nextKey
            k2 = 0
            k3 = 0
        elif self.m_num==2:
            k2 = nextKey
            k3 = 0
        elif self.m_num==3:
            k3 = nextKey
        else:
            pass

        self.m_num += 1
        if (self.m_num > 3):
            self.m_num = 0
        self.m_keySequence = QKeySequence(k0, k1, k2, k3)
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))
        e.accept()
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def setKeySequence(self, sequence):
        if (sequence == self.m_keySequence):
            return
        self.m_num = 0
        self.m_keySequence = sequence
        self.m_lineEdit.setText(self.m_keySequence.toString(QKeySequence.NativeText))

    def keySequence(self):
        return self.m_keySequence

    def translateModifiers(self, state, text):
        result = 0
        if ((state & Qt.ShiftModifier) and (len(text) == 0 or not text[0].isprintable() or text[0].isalpha() or text[0].isspace())):
            result |= Qt.SHIFT
        if (state & Qt.ControlModifier):
            result |= Qt.CTRL
        if (state & Qt.MetaModifier):
            result |= Qt.META
        if (state & Qt.AltModifier):
            result |= Qt.ALT
        return result

    def focusInEvent(self, e):
        self.m_lineEdit.event(e)
        self.m_lineEdit.selectAll()
        super(QtKeySequenceEdit, self).focusInEvent(e)

    def focusOutEvent(self, e):
        self.m_num = 0
        self.m_lineEdit.event(e)
        super(QtKeySequenceEdit, self).focusOutEvent(e)

    def keyPressEvent(self, e):
        self.handleKeyEvent(e)
        e.accept()

    def keyReleaseEvent(self, e):
        self.m_lineEdit.event(e)

    def paintEvent(self, ptQPaintEvent):
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)

    def event(self,e):
        if (e.type() == QEvent.Shortcut or
                e.type() == QEvent.ShortcutOverride  or
                e.type() == QEvent.KeyRelease):
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).event(e)
Exemplo n.º 25
0
class KeySequenceEditor(QQuickItem):

    _logger = _module_logger.getChild('KeySequenceEditor')

    ##############################################

    def __init__(self, parent):

        super().__init__(parent)

        self._default_sequence = QKeySequence()  # default sequence
        self._edited_sequence = QKeySequence()  # current/edited sequence
        self._new_sequence = QKeySequence()  # customised sequence

        self._reset_pressed_keys()

    ##############################################

    def _reset_pressed_keys(self):
        self._logger.info('Clearing pressed keys')
        self._pressed_keys = []

    ##############################################

    default_sequence_changed = Signal()

    @Property(str, notify=default_sequence_changed)
    def default_sequence(self):
        return self._default_sequence.toString()

    ##############################################

    @default_sequence.setter
    def default_sequence(self, default_sequence):

        if default_sequence != self._default_sequence.toString():
            self._default_sequence = QKeySequence(default_sequence,
                                                  QKeySequence.PortableText)
            self._set_edited_sequence('')  # Fixme: why reset ???
            self.new_sequence = ''
            self.default_sequence_changed.emit()
            # This might not always be the case, I'm just lazy.
            self.is_customised_changed.emit()
            self.display_sequence_changed.emit()

    ##############################################

    new_sequence_changed = Signal()

    @Property(str, notify=new_sequence_changed)
    def new_sequence(self):
        return self._new_sequence.toString()

    @new_sequence.setter
    def new_sequence(self, new_sequence):

        if new_sequence != self._new_sequence.toString():
            self._new_sequence = QKeySequence(new_sequence,
                                              QKeySequence.PortableText)
            self._logger.info('Set new sequence to {}'.format(
                self._new_sequence.toString()))
            self.new_sequence_changed.emit()
            self.is_customised_changed.emit()
            self.display_sequence_changed.emit()

    ##############################################

    display_sequence_changed = Signal()

    @Property(str, notify=display_sequence_changed)
    def display_sequence(self):
        """Text to show in the sequence editor"""

        if self.hasActiveFocus():
            # we are editing the sequence
            sequence = self._edited_sequence
        elif self._new_sequence.isEmpty():
            # no new sequence
            sequence = self._default_sequence
        else:
            sequence = self._new_sequence

        return sequence.toString()

    ##############################################

    is_customised_changed = Signal()

    @Property(bool, notify=is_customised_changed)
    def is_customised(self):
        """Flag to indicate a new valid sequence is set"""
        return not self._new_sequence.isEmpty(
        ) and self._new_sequence != self._default_sequence

    ##############################################

    @Slot()
    def reset(self):
        """Reset the sequence to the default one"""
        self._set_edited_sequence(self.default_sequence)
        self.new_sequence = self.default_sequence
        self._reset_pressed_keys()

    ##############################################

    def _set_edited_sequence(self, edited_sequence=''):
        """Update the edited sequence.

        emit *is_customised* and *display_sequence*
        """

        if edited_sequence != self._edited_sequence.toString():
            self._edited_sequence = QKeySequence(edited_sequence,
                                                 QKeySequence.PortableText)
            self._logger.info('Edited sequence changed to {}'.format(
                self._edited_sequence.toString()))
            self.is_customised_changed.emit()
            self.display_sequence_changed.emit()

    ##############################################

    def keyPressEvent(self, event):
        """Handler when a key is pressed.

        * use Escape to leave the control
        * use Enter to accept the sequence

        """

        if event.key() == Qt.Key_Escape:
            self.setFocus(False)

        elif event.key() == Qt.Key_Return:
            self._accept()

        elif not event.isAutoRepeat():
            modifiers = 0
            # event.modifiers().testFlag(...)
            if event.modifiers() & Qt.ControlModifier:
                modifiers |= Qt.CTRL
            if event.modifiers() & Qt.ShiftModifier:
                modifiers |= Qt.SHIFT
            if event.modifiers() & Qt.AltModifier:
                modifiers |= Qt.ALT
            if event.modifiers() & Qt.MetaModifier:
                modifiers |= Qt.META

            if Qt.Key_Shift <= event.key() <= Qt.Key_Meta:
                self._logger.info(
                    'Only modifiers were pressed ({} / {} / {} ignoring'.
                    format(event.text(), _key_name(event.key()),
                           QKeySequence(event.key()).toString()))

            else:
                self._pressed_keys.append(event.key() | modifiers)
                self._logger.info(
                    'Adding key {} / {} / {} with modifiers ({}) to pressed keys'
                    .format(
                        event.text(),
                        _key_name(event.key()),
                        QKeySequence(event.key()).toString(),
                        # UnicodeEncodeError: 'utf-8' codec can't encode character '\udc21' in position 188: surrogates not allowed
                        QKeySequence(self._pressed_keys[-1]).toString(),
                    ))

                sequence = QKeySequence(*self._pressed_keys)  # up to 4 keys
                self._set_edited_sequence(sequence.toString())

                if len(self._pressed_keys) == 4:
                    # That was the last key out of four possible keys end it here.
                    self._accept()

        event.accept()

    ##############################################

    def keyReleaseEvent(self, event):
        event.accept()

    ##############################################

    def focusInEvent(self, event):
        event.accept()
        # The text displaying the shortcut should be cleared when editing begins.
        self.display_sequence_changed.emit()

    ##############################################

    def focusOutEvent(self, event):
        event.accept()
        self._cancel()

    ##############################################

    def _accept(self):
        """Update *new_sequence* if the input is valid."""

        self._logger.info('Attempting to accept input...')

        # If there hasn't been anything new successfully entered yet, check against the original
        # sequence, otherwise check against the latest successfully entered sequence.
        # Note: is_customised() assumes that an empty sequence isn't possible we might want to account
        # for this in the future.
        if ((self._edited_sequence != self._default_sequence)
                or (self.is_customised
                    and self._edited_sequence != self._new_sequence)):
            if self._validate(self._edited_sequence):
                self._logger.info('Input valid')
                self.new_sequence = self._edited_sequence.toString()
            else:
                self._logger.info('Input invalid')
                self._cancel()
        else:
            self._logger.info('Nothing has changed in the input')
            # Nothing's changed.

        self._reset_pressed_keys()
        self.setFocus(False)

    ##############################################

    def _cancel(self):

        self._reset_pressed_keys()
        if self._edited_sequence.isEmpty():
            # If the edited sequence is empty, setting it to an empty string
            # obviously won't change anything, and it will return early.
            # We need the display sequence to update though, so call it here.
            self.display_sequence_changed.emit()
        else:
            self._set_edited_sequence('')

    ##############################################

    def _validate(self, sequence):
        """Method to validate the new sequence"""

        self._logger.info('Validating key sequence {} ...'.format(
            sequence.toString()))
        valid = True  # False
        # do some checks
        return valid
Exemplo n.º 26
0
class QtKeySequenceEdit(QWidget):
    keySequenceChangedSignal = pyqtSignal(QKeySequence)

    def __init__(self, parent=None):
        super(QtKeySequenceEdit, self).__init__(parent)

        self.m_keySequence = QKeySequence()
        self.m_num = 0
        self.m_lineEdit = QLineEdit(self)
        layout = QHBoxLayout(self)
        layout.addWidget(self.m_lineEdit)
        layout.setContentsMargins(0, 0, 0, 0)
        self.m_lineEdit.installEventFilter(self)
        self.m_lineEdit.setReadOnly(True)
        self.m_lineEdit.setFocusProxy(self)
        self.setFocusPolicy(self.m_lineEdit.focusPolicy())
        self.setAttribute(Qt.WA_InputMethodEnabled)

    def eventFilter(self, o, e):
        if o == self.m_lineEdit and e.type() == QEvent.ContextMenu:
            c = e
            menu = self.m_lineEdit.createStandardContextMenu()
            actions = menu.actions()
            for action in actions:
                action.setShortcut(QKeySequence())
                actionString = action.text()
                pos = actionString.rfind('\t')
                if (pos > 0):
                    actionString = actionString[:pos]
                action.setText(actionString)

            actionBefore = None
            if (len(actions) > 0):
                actionBefore = actions[0]
            clearAction = QAction(self.tr("Clear Shortcut"), menu)
            menu.insertAction(actionBefore, clearAction)
            menu.insertSeparator(actionBefore)
            clearAction.setEnabled(not len(self.m_keySequence) <= 0)
            clearAction.triggered.connect(self.slotClearShortcut)
            menu.exec(c.globalPos())
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).eventFilter(o, e)

    def slotClearShortcut(self):
        if len(self.m_keySequence) <= 0:
            return
        self.setKeySequence(QKeySequence())
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def handleKeyEvent(self, e):
        nextKey = e.key()
        if (nextKey == Qt.Key_Control or nextKey == Qt.Key_Shift
                or nextKey == Qt.Key_Meta or nextKey == Qt.Key_Alt
                or nextKey == Qt.Key_Super_L or nextKey == Qt.Key_AltGr):
            return

        nextKey |= self.translateModifiers(e.modifiers(), e.text())
        k0 = 0
        k1 = 0
        k2 = 0
        k3 = 0
        l = len(self.m_keySequence)
        if l == 1:
            k0 = self.m_keySequence[0]
        elif l == 2:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
        elif l == 3:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
        elif l == 4:
            k0 = self.m_keySequence[0]
            k1 = self.m_keySequence[1]
            k2 = self.m_keySequence[2]
            k3 = self.m_keySequence[3]
        if self.m_num == 0:
            k0 = nextKey
            k1 = 0
            k2 = 0
            k3 = 0
        elif self.m_num == 1:
            k1 = nextKey
            k2 = 0
            k3 = 0
        elif self.m_num == 2:
            k2 = nextKey
            k3 = 0
        elif self.m_num == 3:
            k3 = nextKey
        else:
            pass

        self.m_num += 1
        if (self.m_num > 3):
            self.m_num = 0
        self.m_keySequence = QKeySequence(k0, k1, k2, k3)
        self.m_lineEdit.setText(
            self.m_keySequence.toString(QKeySequence.NativeText))
        e.accept()
        self.keySequenceChangedSignal.emit(self.m_keySequence)

    def setKeySequence(self, sequence):
        if (sequence == self.m_keySequence):
            return
        self.m_num = 0
        self.m_keySequence = sequence
        self.m_lineEdit.setText(
            self.m_keySequence.toString(QKeySequence.NativeText))

    def keySequence(self):
        return self.m_keySequence

    def translateModifiers(self, state, text):
        result = 0
        if ((state & Qt.ShiftModifier)
                and (len(text) == 0 or not text[0].isprintable()
                     or text[0].isalpha() or text[0].isspace())):
            result |= Qt.SHIFT
        if (state & Qt.ControlModifier):
            result |= Qt.CTRL
        if (state & Qt.MetaModifier):
            result |= Qt.META
        if (state & Qt.AltModifier):
            result |= Qt.ALT
        return result

    def focusInEvent(self, e):
        self.m_lineEdit.event(e)
        self.m_lineEdit.selectAll()
        super(QtKeySequenceEdit, self).focusInEvent(e)

    def focusOutEvent(self, e):
        self.m_num = 0
        self.m_lineEdit.event(e)
        super(QtKeySequenceEdit, self).focusOutEvent(e)

    def keyPressEvent(self, e):
        self.handleKeyEvent(e)
        e.accept()

    def keyReleaseEvent(self, e):
        self.m_lineEdit.event(e)

    def paintEvent(self, ptQPaintEvent):
        opt = QStyleOption()
        opt.initFrom(self)
        p = QPainter(self)
        self.style().drawPrimitive(QStyle.PE_Widget, opt, p, self)

    def event(self, e):
        if (e.type() == QEvent.Shortcut or e.type() == QEvent.ShortcutOverride
                or e.type() == QEvent.KeyRelease):
            e.accept()
            return True

        return super(QtKeySequenceEdit, self).event(e)
Exemplo n.º 27
0
class KeySequenceButton(QPushButton):
    def __init__(self, parent=None):
        super(KeySequenceButton, self).__init__(parent)
        self.setIcon(icons.get("configure"))
        self._modifierlessAllowed = False
        self._seq = QKeySequence()
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        self._isrecording = False
        self.clicked.connect(self.startRecording)
        self._timer.timeout.connect(self.doneRecording)

    def setKeySequence(self, seq):
        self._seq = seq
        self.updateDisplay()

    def keySequence(self):
        if self._isrecording:
            self.doneRecording()
        return self._seq

    def updateDisplay(self):
        if self._isrecording:
            s = self._recseq.toString(QKeySequence.NativeText).replace(
                '&', '&&')
            if self._modifiers:
                if s: s += ","
                s += QKeySequence(self._modifiers).toString(
                    QKeySequence.NativeText)
            elif self._recseq.isEmpty():
                s = _("Input")
            s += " ..."
        else:
            s = self._seq.toString(QKeySequence.NativeText).replace('&', '&&')
        self.setText(s)

    def isRecording(self):
        return self._isrecording

    def event(self, ev):
        if self._isrecording:
            # prevent Qt from special casing Tab and Backtab
            if ev.type() == QEvent.KeyPress:
                self.keyPressEvent(ev)
                return True
        return super(KeySequenceButton, self).event(ev)

    def keyPressEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyPressEvent(ev)
        if ev.isAutoRepeat():
            return
        modifiers = int(ev.modifiers()
                        & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()

        key = ev.key()
        # check if key is a modifier or a character key without modifier (and if that is allowed)
        if (
                # don't append the key if the key is -1 (garbage) or a modifier ...
                key not in (-1, Qt.Key_AltGr, Qt.Key_Shift, Qt.Key_Control,
                            Qt.Key_Alt, Qt.Key_Meta, Qt.Key_Menu)
                # or if this is the first key and without modifier and modifierless keys are not allowed
                and (self._modifierlessAllowed or self._recseq.count() > 0
                     or modifiers & ~Qt.SHIFT or not ev.text() or
                     (modifiers & Qt.SHIFT and key in
                      (Qt.Key_Return, Qt.Key_Space, Qt.Key_Tab, Qt.Key_Backtab,
                       Qt.Key_Backspace, Qt.Key_Delete, Qt.Key_Escape)))):
            # change Shift+Backtab into Shift+Tab
            if key == Qt.Key_Backtab and modifiers & Qt.SHIFT:
                key = Qt.Key_Tab | modifiers
            # remove the Shift modifier if it doesn't make sense
#            elif (Qt.Key_Exclam <= key <= Qt.Key_At
#                  or Qt.Key_Z < key <= 0x0ff):
#                key = key | (modifiers & ~Qt.SHIFT)
            else:
                key = key | modifiers

            # append max. 4 keystrokes
            if self._recseq.count() < 4:
                l = list(self._recseq)
                l.append(key)
                self._recseq = QKeySequence(*l)

        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()

    def keyReleaseEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyReleaseEvent(ev)
        modifiers = int(ev.modifiers()
                        & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()

        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()

    def hideEvent(self, ev):
        if self._isrecording:
            self.cancelRecording()
        super(KeySequenceButton, self).hideEvent(ev)

    def controlTimer(self):
        if self._modifiers or self._recseq.isEmpty():
            self._timer.stop()
        else:
            self._timer.start(600)

    def startRecording(self):
        self.setFocus(True)  # because of QTBUG 17810
        self.setDown(True)
        self.setStyleSheet("text-align: left;")
        self._isrecording = True
        self._recseq = QKeySequence()
        self._modifiers = int(QApplication.keyboardModifiers()
                              & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        self.grabKeyboard()
        self.updateDisplay()

    def doneRecording(self):
        self._seq = self._recseq
        self.cancelRecording()
        self.clearFocus()
        self.parentWidget().keySequenceChanged.emit(self.parentWidget().num())

    def cancelRecording(self):
        if not self._isrecording:
            return
        self.setDown(False)
        self.setStyleSheet(None)
        self._isrecording = False
        self.releaseKeyboard()
        self.updateDisplay()
Exemplo n.º 28
0
                return
            else:
                self.key_seq_list[11] = key_seq
                # self.shortcut_settings.setValue("location_right", key_seq)
                self.location_right_label.setText(key_seq.toString())

    def accept(self):
        print(self.key_seq_list)
        self.shortcut_settings.setValue("show_hide_detail",
                                        self.key_seq_list[3])
        self.shortcut_settings.setValue("show_hide_company",
                                        self.key_seq_list[4])
        self.shortcut_settings.setValue("page_down", self.key_seq_list[6])
        self.shortcut_settings.setValue("page_up", self.key_seq_list[7])
        self.shortcut_settings.setValue("location_up", self.key_seq_list[8])
        self.shortcut_settings.setValue("location_down", self.key_seq_list[9])
        self.shortcut_settings.setValue("location_left", self.key_seq_list[10])
        self.shortcut_settings.setValue("location_right",
                                        self.key_seq_list[11])
        # 接下来 要那拿着这些设置去配置快捷键
        self.reset_shortcut_signal.emit()
        super(ShortCutSetDialogControl, self).accept()


if __name__ == '__main__':
    x = QKeySequence(Qt.CTRL + Qt.Key_Insert)
    y = QKeySequence(Qt.CTRL + Qt.Key_Insert)
    print(x == y)
    print(str(x))
    print(x.toString())
Exemplo n.º 29
0
class ShortCutSetDialogControl(QDialog, Ui_shortCutDialog):
    reset_shortcut_signal = pyqtSignal()

    def __init__(self, parent):
        super(ShortCutSetDialogControl, self).__init__(parent)
        self.setupUi(self)
        # self.setAttribute(Qt.WA_DeleteOnClose)
        # self.setWindowFlags(Qt.WindowStaysOnTopHint)
        self.shortcut_settings = QSettings("short_cut")
        self.input_short_cut_dialog_control = InputShortCutDialogControl(self)
        self.key_seq_list = [None] * 16
        self.move_right_label.setText(
            QKeySequence(Qt.ALT + Qt.Key_Space).toString())
        self.switch_behind_label.setText(
            QKeySequence(Qt.ALT + Qt.Key_Down).toString())
        self.switch_front_label.setText(
            QKeySequence(Qt.ALT + Qt.Key_Up).toString())
        self.hide_detail_company_label.setText(
            QKeySequence(Qt.ALT + Qt.Key_Z).toString())
        #
        self.sell_new_option_label.setText(
            QKeySequence(Qt.CTRL + Qt.Key_Insert).toString())
        self.this_module_confirm_label.setText(
            QKeySequence(Qt.CTRL + Qt.Key_Enter).toString())
        self.add_price_label.setText(
            QKeySequence(Qt.CTRL + Qt.Key_PageUp).toString())
        self.recove_price_label.setText(
            QKeySequence(Qt.CTRL + Qt.Key_Home).toString())

        # self.show_hide_detail_seq = self.shortcut_settings.value("show_hide_detail")
        # if self.show_hide_detail_seq:
        #     self.show_hide_detail_label.setText(self.show_hide_detail_seq)
        #
        # self.show_hide_company_seq = self.shortcut_settings.value("show_hide_company")
        # if self.show_hide_company_seq:
        #     self.show_hide_company_label.setText(self.show_hide_company_seq)
        #
        # self.page_down_seq = self.shortcut_settings.value("page_down")
        # if self.page_down_seq:
        #     self.page_down_label.setText(self.page_down_seq)
        #
        # self.page_up_seq = self.shortcut_settings.value("page_up")
        # if self.page_up_seq:
        #     self.page_up_label.setText(self.page_up_seq)
        #
        # self.location_up_seq = self.shortcut_settings.value("location_up")
        # if self.location_up_seq:
        #     self.location_up_label.setText(self.location_up_seq)
        #
        # self.location_right_seq = self.shortcut_settings.value("location_right")
        # if self.location_right_seq:
        #     self.location_right_label.setText(self.location_right_seq)
        #
        # self.location_left_seq = self.shortcut_settings.value("location_left")
        # if self.location_left_seq:
        #     self.location_left_label.setText(self.location_left_seq)
        #
        # self.location_down_seq = self.shortcut_settings.value("location_down")
        # if self.location_down_seq:
        #     self.location_down_label.setText(self.location_down_seq)
        self.show_hide_detail_seq = None
        self.show_hide_company_seq = None
        self.page_down_seq = None
        self.page_up_seq = None
        self.location_up_seq = None
        self.location_right_seq = None
        self.location_left_seq = None
        self.location_down_seq = None

    def set_seq(self):
        # self.move_right_label.setText(QKeySequence(Qt.ALT + Qt.Key_Tab).toString())
        # self.switch_behind_label.setText(QKeySequence(Qt.ALT + Qt.Key_Down).toString())
        # self.switch_front_label.setText(QKeySequence(Qt.ALT + Qt.Key_Up).toString())
        # self.hide_detail_company_label.setText(QKeySequence(Qt.ALT + Qt.Key_Z).toString())
        # #
        # self.sell_new_option_label.setText(QKeySequence(Qt.CTRL + Qt.Key_Insert).toString())
        # self.this_module_confirm_label.setText(QKeySequence(Qt.CTRL + Qt.Key_Enter).toString())
        # self.add_price_label.setText(QKeySequence(Qt.CTRL + Qt.Key_PageUp).toString())
        # self.recove_price_label.setText(QKeySequence(Qt.CTRL + Qt.Key_Home).toString())

        self.show_hide_detail_seq = QKeySequence(
            self.shortcut_settings.value("show_hide_detail"))

        if self.show_hide_detail_seq:

            self.show_hide_detail_label.setText(
                self.show_hide_detail_seq.toString())

        self.show_hide_company_seq = QKeySequence(
            self.shortcut_settings.value("show_hide_company"))
        if self.show_hide_company_seq:
            self.show_hide_company_label.setText(
                self.show_hide_company_seq.toString())

        self.page_down_seq = QKeySequence(
            self.shortcut_settings.value("page_down"))
        if self.page_down_seq:
            self.page_down_label.setText(self.page_down_seq.toString())

        self.page_up_seq = QKeySequence(
            self.shortcut_settings.value("page_up"))
        if self.page_up_seq:
            self.page_up_label.setText(self.page_up_seq.toString())

        self.location_up_seq = QKeySequence(
            self.shortcut_settings.value("location_up"))
        if self.location_up_seq:
            self.location_up_label.setText(self.location_up_seq.toString())

        self.location_right_seq = QKeySequence(
            self.shortcut_settings.value("location_right"))
        if self.location_right_seq:
            self.location_right_label.setText(
                self.location_right_seq.toString())

        self.location_left_seq = QKeySequence(
            self.shortcut_settings.value("location_left"))
        if self.location_left_seq:

            self.location_left_label.setText(self.location_left_seq.toString())

        self.location_down_seq = QKeySequence(
            self.shortcut_settings.value("location_down"))
        if self.location_down_seq:

            self.location_down_label.setText(self.location_down_seq.toString())

        self.key_seq_list = [
            QKeySequence(Qt.ALT + Qt.Key_Tab),
            QKeySequence(Qt.ALT + Qt.Key_Down),
            QKeySequence(Qt.ALT + Qt.Key_Up), self.show_hide_detail_seq,
            self.show_hide_company_seq,
            QKeySequence(Qt.ALT + Qt.Key_Z), self.page_down_seq,
            self.page_up_seq, self.location_up_seq, self.location_right_seq,
            self.location_left_seq, self.location_down_seq,
            QKeySequence(Qt.CTRL + Qt.Key_Insert),
            QKeySequence(Qt.CTRL + Qt.Key_Enter),
            QKeySequence(Qt.CTRL + Qt.Key_PageUp),
            QKeySequence(Qt.CTRL + Qt.Key_Home)
        ]

    @pyqtSlot()
    def on_show_hide_detail_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "显/隐明细")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[3] = key_seq
                # self.shortcut_settings.setValue("show_hide_detail", key_seq)
                self.show_hide_detail_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_show_hide_company_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "显/隐对公")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[4] = key_seq
                # self.shortcut_settings.setValue("show_hide_company", key_seq)
                self.show_hide_company_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_page_down_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "向下翻页")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[6] = key_seq
                # self.shortcut_settings.setValue("page_down", key_seq)
                self.page_down_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_page_up_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "向上翻页")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[7] = key_seq
                # self.shortcut_settings.setValue("page_up", key_seq)
                self.page_up_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_location_up_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "定位最上")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[8] = key_seq
                # self.shortcut_settings.setValue("location_up", key_seq)
                self.location_up_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_location_down_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "定位最下")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[9] = key_seq
                print(key_seq)
                # self.shortcut_settings.setValue("location_down",key_seq)
                self.location_down_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_location_left_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "定位最左")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[10] = key_seq
                # self.shortcut_settings.setValue("location_left", key_seq)
                self.location_left_label.setText(key_seq.toString())

    @pyqtSlot()
    def on_location_right_toolButton_clicked(self):
        ''''''
        self.input_short_cut_dialog_control.change_set_who_label_signal.emit(
            "定位最右")
        self.input_short_cut_dialog_control.lineEdit.setFocus()
        self.input_short_cut_dialog_control.exec_()
        key_seq = self.input_short_cut_dialog_control.get_keysequence()
        self.input_short_cut_dialog_control.lineEdit.clear()
        if key_seq:
            if key_seq in self.key_seq_list:
                QMessageBox.warning(self, "错误", "快捷键不可重复")
                return
            else:
                self.key_seq_list[11] = key_seq
                # self.shortcut_settings.setValue("location_right", key_seq)
                self.location_right_label.setText(key_seq.toString())

    def accept(self):
        print(self.key_seq_list)
        self.shortcut_settings.setValue("show_hide_detail",
                                        self.key_seq_list[3])
        self.shortcut_settings.setValue("show_hide_company",
                                        self.key_seq_list[4])
        self.shortcut_settings.setValue("page_down", self.key_seq_list[6])
        self.shortcut_settings.setValue("page_up", self.key_seq_list[7])
        self.shortcut_settings.setValue("location_up", self.key_seq_list[8])
        self.shortcut_settings.setValue("location_down", self.key_seq_list[9])
        self.shortcut_settings.setValue("location_left", self.key_seq_list[10])
        self.shortcut_settings.setValue("location_right",
                                        self.key_seq_list[11])
        # 接下来 要那拿着这些设置去配置快捷键
        self.reset_shortcut_signal.emit()
        super(ShortCutSetDialogControl, self).accept()
Exemplo n.º 30
0
class KeySequenceButton(QPushButton):
    
    def __init__(self, parent=None):
        super(KeySequenceButton, self).__init__(parent)
        self.setIcon(icons.get("configure"))
        self._modifierlessAllowed = False
        self._seq = QKeySequence()
        self._timer = QTimer()
        self._timer.setSingleShot(True)
        self._isrecording = False
        self.clicked.connect(self.startRecording)
        self._timer.timeout.connect(self.doneRecording)

    def setKeySequence(self, seq):
        self._seq = seq
        self.updateDisplay()

    def keySequence(self):
        if self._isrecording:
            self.doneRecording()
        return self._seq
    
    def updateDisplay(self):
        if self._isrecording:
            s = self._recseq.toString(QKeySequence.NativeText).replace('&', '&&')
            if self._modifiers:
                if s: s += ","
                s += QKeySequence(self._modifiers).toString(QKeySequence.NativeText)
            elif self._recseq.isEmpty():
                s = _("Input")
            s += " ..."
        else:
            s = self._seq.toString(QKeySequence.NativeText).replace('&', '&&')
        self.setText(s)

    def isRecording(self):
        return self._isrecording
        
    def event(self, ev):
        if self._isrecording:
            # prevent Qt from special casing Tab and Backtab
            if ev.type() == QEvent.KeyPress:
                self.keyPressEvent(ev)
                return True
        return super(KeySequenceButton, self).event(ev)
        
    def keyPressEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyPressEvent(ev)
        if ev.isAutoRepeat():
            return
        modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()
        
        key = ev.key()
        # check if key is a modifier or a character key without modifier (and if that is allowed)
        if (
            # don't append the key if the key is -1 (garbage) or a modifier ...
            key not in (-1, Qt.Key_AltGr, Qt.Key_Shift, Qt.Key_Control,
                            Qt.Key_Alt, Qt.Key_Meta, Qt.Key_Menu)
            # or if this is the first key and without modifier and modifierless keys are not allowed
            and (self._modifierlessAllowed
                 or self._recseq.count() > 0
                 or modifiers & ~Qt.SHIFT
                 or not ev.text()
                 or (modifiers & Qt.SHIFT
                     and key in (Qt.Key_Return, Qt.Key_Space, Qt.Key_Tab, Qt.Key_Backtab,
                                 Qt.Key_Backspace, Qt.Key_Delete, Qt.Key_Escape)))):
            # change Shift+Backtab into Shift+Tab
            if key == Qt.Key_Backtab and modifiers & Qt.SHIFT:
                key = Qt.Key_Tab | modifiers
            # remove the Shift modifier if it doesn't make sense
#            elif (Qt.Key_Exclam <= key <= Qt.Key_At
#                  or Qt.Key_Z < key <= 0x0ff):
#                key = key | (modifiers & ~Qt.SHIFT)
            else:
                key = key | modifiers
            
            # append max. 4 keystrokes
            if self._recseq.count() < 4:
                l = list(self._recseq)
                l.append(key)
                self._recseq = QKeySequence(*l)
        
        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()
        
    def keyReleaseEvent(self, ev):
        if not self._isrecording:
            return super(KeySequenceButton, self).keyReleaseEvent(ev)
        modifiers = int(ev.modifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        ev.accept()
        
        self._modifiers = modifiers
        self.controlTimer()
        self.updateDisplay()
    
    def hideEvent(self, ev):
        if self._isrecording:
            self.cancelRecording()
        super(KeySequenceButton, self).hideEvent(ev)
        
    def controlTimer(self):
        if self._modifiers or self._recseq.isEmpty():
            self._timer.stop()
        else:
            self._timer.start(600)
    
    def startRecording(self):
        self.setFocus(True) # because of QTBUG 17810
        self.setDown(True)
        self.setStyleSheet("text-align: left;")
        self._isrecording = True
        self._recseq = QKeySequence()
        self._modifiers = int(QApplication.keyboardModifiers() & (Qt.SHIFT | Qt.CTRL | Qt.ALT | Qt.META))
        self.grabKeyboard()
        self.updateDisplay()
        
    def doneRecording(self):
        self._seq = self._recseq
        self.cancelRecording()
        self.clearFocus()
        self.parentWidget().keySequenceChanged.emit(self.parentWidget().num())
        
    def cancelRecording(self):
        if not self._isrecording:
            return
        self.setDown(False)
        self.setStyleSheet(None)
        self._isrecording = False
        self.releaseKeyboard()
        self.updateDisplay()
Exemplo n.º 31
0
 def shortcut_help_to_string(self, shortcut, help_text):
     """Formats a shortcut string and help text."""
     return (QKeySequence.toString(QKeySequence(shortcut),
                                   QKeySequence.NativeText) + '\t' +
             help_text + '\n')
Exemplo n.º 32
0
 def setKey(self, key_string):
     self.key_string = key_string
     qkeyseq = QKeySequence(key_string, QKeySequence.PortableText)
     native_key_string = qkeyseq.toString(format=QKeySequence.NativeText)
     self.setText(native_key_string)