Esempio n. 1
0
    def setup_context_menu(self):
        """Reimplements ShellBaseWidget method"""
        ShellBaseWidget.setup_context_menu(self)
        self.copy_without_prompts_action = create_action(
            self,
            _("Copy without prompts"),
            icon=ima.icon('copywop'),
            triggered=self.copy_without_prompts)

        clear_line_action = create_action(
            self,
            _("Clear line"),
            QKeySequence(CONF.get_shortcut('console', 'Clear line')),
            icon=ima.icon('editdelete'),
            tip=_("Clear line"),
            triggered=self.clear_line)

        clear_action = create_action(
            self,
            _("Clear shell"),
            QKeySequence(CONF.get_shortcut('console', 'Clear shell')),
            icon=ima.icon('editclear'),
            tip=_("Clear shell contents ('cls' command)"),
            triggered=self.clear_terminal)

        add_actions(self.menu, (self.copy_without_prompts_action,
                                clear_line_action, clear_action))
Esempio n. 2
0
    def __init__(self, parent, term_url='http://127.0.0.1:8070'):
        """Webview main constructor."""
        WebView.__init__(self, parent)
        self.parent = parent
        self.copy_action = create_action(self,
                                         _("Copy text"),
                                         icon=ima.icon('editcopy'),
                                         triggered=self.copy,
                                         shortcut='Ctrl+Alt+C')
        self.paste_action = create_action(self,
                                          _("Paste text"),
                                          icon=ima.icon('editpaste'),
                                          triggered=self.paste,
                                          shortcut='Ctrl+Alt+V')
        self.term_url = QUrl(term_url)
        self.load(self.term_url)
        copy_shortcut = QShortcut(QKeySequence("Ctrl+Alt+C"), self, self.copy)
        copy_shortcut.setContext(Qt.WidgetWithChildrenShortcut)

        paste_shortcut = QShortcut(QKeySequence("Ctrl+Alt+V"), self,
                                   self.paste)
        paste_shortcut.setContext(Qt.WidgetWithChildrenShortcut)

        if WEBENGINE:
            self.document = self.page()
        else:
            self.document = self.page().mainFrame()

        self.initial_y_pos = 0
Esempio n. 3
0
 def add_actions_to_context_menu(self, menu):
     """Add actions to IPython widget context menu"""
     inspect_action = create_action(
         self,
         _("Inspect current object"),
         QKeySequence(get_shortcut('console', 'inspect current object')),
         icon=ima.icon('MessageBoxInformation'),
         triggered=self.inspect_object)
     clear_line_action = create_action(self,
                                       _("Clear line or block"),
                                       QKeySequence("Shift+Escape"),
                                       icon=ima.icon('editdelete'),
                                       triggered=self.clear_line)
     reset_namespace_action = create_action(self,
                                            _("Reset namespace"),
                                            QKeySequence("Ctrl+Alt+R"),
                                            triggered=self.reset_namespace)
     clear_console_action = create_action(
         self,
         _("Clear console"),
         QKeySequence(get_shortcut('console', 'clear shell')),
         icon=ima.icon('editclear'),
         triggered=self.clear_console)
     quit_action = create_action(self,
                                 _("&Quit"),
                                 icon=ima.icon('exit'),
                                 triggered=self.exit_callback)
     add_actions(
         menu,
         (None, inspect_action, clear_line_action, clear_console_action,
          reset_namespace_action, None, quit_action))
     return menu
Esempio n. 4
0
    def _setup_actions(self):
        """Creates the main window actions."""
        # Show/hide callable objects
        self.toggle_show_callable_action = QAction(
            _("Show callable attributes"),
            self,
            checkable=True,
            shortcut=QKeySequence("Alt+C"),
            statusTip=_("Shows/hides attributes that are callable "
                        "(functions, methods, etc)"))
        self.toggle_show_callable_action.toggled.connect(
            self._proxy_tree_model.setShowCallables)
        self.toggle_show_callable_action.toggled.connect(
            self.obj_tree.resize_columns_to_contents)

        # Show/hide special attributes
        self.toggle_show_special_attribute_action = QAction(
            _("Show __special__ attributes"),
            self,
            checkable=True,
            shortcut=QKeySequence("Alt+S"),
            statusTip=_("Shows or hides __special__ attributes"))
        self.toggle_show_special_attribute_action.toggled.connect(
            self._proxy_tree_model.setShowSpecialAttributes)
        self.toggle_show_special_attribute_action.toggled.connect(
            self.obj_tree.resize_columns_to_contents)
Esempio n. 5
0
    def apply_shortcuts(self):
        """
        Apply shortcuts settings to all widgets/plugins.
        """
        toberemoved = []

        # TODO: Check shortcut existence based on action existence, so that we
        # can update shortcut names without showing the old ones on the
        # preferences
        for index, (qobject, context, name, add_shortcut_to_tip,
                    plugin_name) in enumerate(self._shortcut_data):
            try:
                shortcut_sequence = self.get_shortcut(context, name,
                                                      plugin_name)
            except (configparser.NoSectionError, configparser.NoOptionError):
                # If shortcut does not exist, save it to CONF. This is an
                # action for which there is no shortcut assigned (yet) in
                # the configuration
                self.set_shortcut(context, name, '', plugin_name)
                shortcut_sequence = ''

            if shortcut_sequence:
                keyseq = QKeySequence(shortcut_sequence)
            else:
                # Needed to remove old sequences that were cleared.
                # See spyder-ide/spyder#12992
                keyseq = QKeySequence()

            # Do not register shortcuts for the toggle view action.
            # The shortcut will be displayed only on the menus and handled by
            # about to show/hide signals.
            if (name.startswith('switch to')
                    and isinstance(qobject, SpyderAction)):
                keyseq = QKeySequence()

            try:
                if isinstance(qobject, QAction):
                    if (sys.platform == 'darwin'
                            and qobject._shown_shortcut == 'missing'):
                        qobject._shown_shortcut = keyseq
                    else:
                        qobject.setShortcut(keyseq)

                    if add_shortcut_to_tip:
                        add_shortcut_to_tooltip(qobject, context, name)

                elif isinstance(qobject, QShortcut):
                    qobject.setKey(keyseq)

            except RuntimeError:
                # Object has been deleted
                toberemoved.append(index)

        for index in sorted(toberemoved, reverse=True):
            self._shortcut_data.pop(index)

        self.sig_shortcuts_updated.emit()
Esempio n. 6
0
    def __init__(self, parent, widthSpace=10):
        super().__init__()

        self.parent = parent

        self.widthSpace = widthSpace
        self.dateFmt = "%d %b %Y"

        self.headerLabels = [
            'Date', 'Time', 'Distance (km)', 'Avg. speed\n(km/h)', 'Calories',
            'Gear'
        ]
        self.setHeaderLabels(self.headerLabels)
        self.header().setStretchLastSection(False)
        # make header tall enough for two rows of text (avg speed has line break)
        font = self.header().font()
        metrics = QFontMetrics(font)
        height = metrics.height()
        self.header().setMinimumHeight(height * 2)
        # align header text centrally
        for idx in range(len(self.headerLabels)):
            self.headerItem().setTextAlignment(idx, Qt.AlignCenter)

        self.setSelectionMode(QAbstractItemView.ExtendedSelection)

        self.makeTree()

        self.sortColumn = None
        self.sortDescending = [True for _ in range(len(self.headerLabels))]
        self.header().setSectionsClickable(True)
        self.header().sectionClicked.connect(self.sortTree)

        self.currentItemChanged.connect(self._itemChanged)

        self.itemSelectionChanged.connect(self._summariseSelected)

        self.sortTree(0)

        msg = "Browse all sessions, grouped by month. Click on the headers \n"
        msg += "to sort by that metric in ascending or descending order.\n"
        msg += "Click on a session to highlight it in the plot."
        self.setToolTip(msg)

        self.editAction = QAction("Edit")
        self.editAction.setShortcut(QKeySequence("Ctrl+E"))
        self.editAction.triggered.connect(self._editItems)
        self.addAction(self.editAction)

        self.mergeAction = QAction("Merge")
        self.mergeAction.setShortcut(QKeySequence("Ctrl+M"))
        self.mergeAction.triggered.connect(self.combineRows)
        self.addAction(self.mergeAction)

        self.setContextMenuPolicy(Qt.CustomContextMenu)
        self.customContextMenuRequested.connect(self._showContextMenu)
Esempio n. 7
0
    def shortcut_text(self, name_or_enum: str):
        # shortcut is always cast to string
        # but somtimes it is a key str "PgUp" and sometimes the QKeySequence.StandardKey enum value

        # https://doc.qt.io/qtforpython/PySide2/QtGui/QKeySequence.html
        # A QApplication instance must have been constructed before a QKeySequence is created; otherwise, your application may crash.

        try:
            enum_val = int(name_or_enum)
            ks = QKeySequence(QKeySequence.StandardKey(enum_val))
        except ValueError:
            ks = QKeySequence(name_or_enum)

        text = ks.toString(QKeySequence.NativeText)
        return f' [{text}]' if text else ''
Esempio n. 8
0
    def register_plugin(self):
        """Register plugin in Spyder's main window"""
        self.main.add_dockwidget(self)
        self.findinfiles.result_browser.sig_edit_goto.connect(
            self.main.editor.load)
        self.findinfiles.find_options.redirect_stdio.connect(
            self.main.redirect_internalshell_stdio)
        self.main.workingdirectory.refresh_findinfiles.connect(self.refreshdir)
        self.main.projects.sig_project_loaded.connect(self.set_project_path)
        self.main.projects.sig_project_closed.connect(self.unset_project_path)
        self.main.editor.open_file_update.connect(self.set_current_opened_file)

        findinfiles_action = create_action(
            self,
            _("&Find in files"),
            icon=ima.icon('findf'),
            triggered=self.switch_to_plugin,
            shortcut=QKeySequence(self.shortcut),
            context=Qt.WidgetShortcut,
            tip=_("Search text in multiple files"))

        self.main.search_menu_actions += [MENU_SEPARATOR, findinfiles_action]
        self.main.search_toolbar_actions += [
            MENU_SEPARATOR, findinfiles_action
        ]
        self.refreshdir()
Esempio n. 9
0
    def event(self, event):
        """Grab all keyboard input."""
        if event.type() == QEvent.ShortcutOverride:
            key = event.key()
            modifiers = event.modifiers()

            if modifiers & Qt.ShiftModifier:
                key += Qt.SHIFT
            if modifiers & Qt.ControlModifier:
                key += Qt.CTRL
            if modifiers & Qt.AltModifier:
                key += Qt.ALT
            if modifiers & Qt.MetaModifier:
                key += Qt.META

            sequence = QKeySequence(key).toString(QKeySequence.PortableText)

            if sequence == 'Ctrl+Alt+Shift+T':
                event.ignore()
                return False
            elif sequence == 'Ctrl+Shift+C':
                self.copy()
            elif sequence == 'Ctrl+Shift+V':
                self.paste()
            event.accept()
            return True

        return WebView.event(self, event)
Esempio n. 10
0
    def __init__(self, qapp, name, parentWinName=None):
        super(MainWindow, self).__init__()

        self.qapp = qapp
        self.name = name

        self.panels = qapp.panels
        self.dragState = DragState.placed
        self.qapp.panels.ezm

        if not parentWinName is None:
            self.setParent(self.qapp.windows[parentWinName])
            self.setWindowFlags(self.windowFlags() | Qt.Tool)
            #self.setWindowFlags(self.windowFlags() | Qt.WindowStaysOnTopHint)

        self.container = self.qapp.panels.ezm.new_container(self, self.name)
        self.setCentralWidget(self.container)

        self.setWindowTitle(f'[{self.name}]')

        self.createMenus()
        self.createStatusBar()

        #Hiding panelsDialog will disable all shortcuts
        sc = QShortcut(
            QKeySequence("Ctrl+Shift+Alt+F12"), self, lambda: self.qapp.
            panelsDialog.setVisible(not self.qapp.panelsDialog.isVisible()))
        sc.setContext(Qt.ApplicationShortcut)

        self.moveQueued.connect(self.moveWindow, Qt.QueuedConnection)

        self.activeCategory = None
        self.activePanId = None
        self.priorHoverButton = None
Esempio n. 11
0
    def data(self, index, role=Qt.DisplayRole):
        """Qt Override."""
        row = index.row()
        if not index.isValid() or not (0 <= row < len(self.shortcuts)):
            return to_qvariant()

        shortcut = self.shortcuts[row]
        key = shortcut.key
        column = index.column()

        if role == Qt.DisplayRole:
            if column == CONTEXT:
                return to_qvariant(shortcut.context)
            elif column == NAME:
                color = self.text_color
                if self._parent == QApplication.focusWidget():
                    if self.current_index().row() == row:
                        color = self.text_color_highlight
                    else:
                        color = self.text_color
                text = self.rich_text[row]
                text = '<p style="color:{0}">{1}</p>'.format(color, text)
                return to_qvariant(text)
            elif column == SEQUENCE:
                text = QKeySequence(key).toString(QKeySequence.NativeText)
                return to_qvariant(text)
            elif column == SEARCH_SCORE:
                # Treating search scores as a table column simplifies the
                # sorting once a score for a specific string in the finder
                # has been defined. This column however should always remain
                # hidden.
                return to_qvariant(self.scores[row])
        elif role == Qt.TextAlignmentRole:
            return to_qvariant(int(Qt.AlignHCenter | Qt.AlignVCenter))
        return to_qvariant()
Esempio n. 12
0
def create_action(parent,
                  text,
                  on_triggered=None,
                  shortcut=None,
                  shortcut_context=None,
                  icon_name=None):
    """Create a QAction based on the give properties

    :param parent: The parent object
    :param text: Text string to display
    :param on_triggered: An optional slot to call on the triggered signal
    :param shortcut: An optional shortcut
    :param shortcut_context: An optional context for the supplied shortcut.
    Only applies if a shortcut has been given
    :param icon_name: The name of the qt awesome uri for an icon.
    :return: A new QAction object
    """
    action = QAction(text, parent)
    if on_triggered is not None:
        action.triggered.connect(on_triggered)
    if shortcut is not None:
        if isinstance(shortcut, tuple) or isinstance(shortcut, list):
            qshortcuts = [QKeySequence(s) for s in shortcut]
            action.setShortcuts(qshortcuts)
        else:
            action.setShortcut(shortcut)

        if shortcut_context is not None:
            action.setShortcutContext(shortcut_context)
    if icon_name is not None:
        action.setIcon(get_icon(icon_name))

    return action
Esempio n. 13
0
 def set_sequence_from_str(self, sequence):
     """
     This is a convenience method to set the new QKeySequence of the
     shortcut editor from a string.
     """
     self._qsequences = [QKeySequence(s) for s in sequence.split(', ')]
     self.update_warning()
Esempio n. 14
0
    def _create_dockwidget(self):
        """Add to parent QMainWindow as a dock widget"""
        # Creating dock widget
        dock = SpyderDockWidget(self.get_plugin_title(), self.main)

        # Set properties
        dock.setObjectName(self.__class__.__name__ + "_dw")
        dock.setAllowedAreas(dock.ALLOWED_AREAS)
        dock.setFeatures(dock.FEATURES)
        dock.setWidget(self)
        self._update_margins()
        dock.visibilityChanged.connect(self._visibility_changed)
        dock.topLevelChanged.connect(self._on_top_level_changed)
        dock.sig_plugin_closed.connect(self._plugin_closed)
        self.dockwidget = dock

        # NOTE: Don't use the default option of CONF.get to assign a
        # None shortcut to plugins that don't have one. That will mess
        # the creation of our Keyboard Shortcuts prefs page
        try:
            context = '_'
            name = 'switch to {}'.format(self.CONF_SECTION)
            self.shortcut = CONF.get_shortcut(context,
                                              name,
                                              plugin_name=self.CONF_SECTION)
        except (configparser.NoSectionError, configparser.NoOptionError):
            pass

        if self.shortcut is not None and self.main is not None:
            sc = QShortcut(QKeySequence(self.shortcut), self.main,
                           self.switch_to_plugin)
            self.register_shortcut(sc, "_",
                                   "Switch to {}".format(self.CONF_SECTION))

        return (dock, dock.LOCATION)
Esempio n. 15
0
    def create_dockwidget(self):
        """Add to parent QMainWindow as a dock widget"""

        # This is not clear yet why the following do not work...
        # (see Issue #880)
        ##         # Using Qt.Window window flags solves Issue #880 (detached dockwidgets
        ##         # are not painted after restarting Spyder and restoring their hexstate)
        ##         # but it does not work with PyQt <=v4.7 (dockwidgets can't be docked)
        ##         # or non-Windows platforms (lot of warnings are printed out)
        ##         # (so in those cases, we use the default window flags: Qt.Widget):
        ##         flags = Qt.Widget if is_old_pyqt or os.name != 'nt' else Qt.Window
        dock = SpyderDockWidget(self.get_plugin_title(), self.main)  #, flags)

        dock.setObjectName(self.__class__.__name__ + "_dw")
        dock.setAllowedAreas(self.ALLOWED_AREAS)
        dock.setFeatures(self.FEATURES)
        dock.setWidget(self)
        self.update_margins()
        dock.visibilityChanged.connect(self.visibility_changed)
        dock.plugin_closed.connect(self.plugin_closed)
        self.dockwidget = dock
        if self.shortcut is not None:
            sc = QShortcut(QKeySequence(self.shortcut), self.main,
                           self.switch_to_plugin)
            self.register_shortcut(sc, "_", "Switch to %s" % self.CONF_SECTION)
        return (dock, self.LOCATION)
Esempio n. 16
0
    def event(self, event):
        """Grab all keyboard input."""
        if event.type() == QEvent.ShortcutOverride:
            key = event.key()
            modifiers = event.modifiers()

            if modifiers & Qt.ShiftModifier:
                key += Qt.SHIFT
            if modifiers & Qt.ControlModifier:
                key += Qt.CTRL
            if modifiers & Qt.AltModifier:
                key += Qt.ALT
            if modifiers & Qt.MetaModifier:
                key += Qt.META

            sequence = QKeySequence(key).toString(QKeySequence.PortableText)
            if sequence == self.CONF.get_shortcut(CONF_SECTION, 'copy'):
                self.copy()
            elif sequence == self.CONF.get_shortcut(CONF_SECTION, 'paste'):
                self.paste()
            elif sequence == self.CONF.get_shortcut(CONF_SECTION, 'clear'):
                self.clear()
            else:
                event.ignore()
                return False
            event.accept()
            return True

        return WebView.event(self, event)
Esempio n. 17
0
    def keyPressEvent(self, event):
        """Qt override method."""
        key = event.key()
        modifiers = event.modifiers()

        if modifiers & Qt.ShiftModifier:
            key += Qt.SHIFT
        if modifiers & Qt.ControlModifier:
            key += Qt.CTRL
        if modifiers & Qt.AltModifier:
            key += Qt.ALT
        if modifiers & Qt.MetaModifier:
            key += Qt.META

        sequence = QKeySequence(key).toString(QKeySequence.PortableText)
        if event == QKeySequence.Paste:
            self.paste()
        elif sequence == self.CONF.get_shortcut(CONF_SECTION, 'copy'):
            self.copy()
        elif sequence == self.CONF.get_shortcut(CONF_SECTION, 'paste'):
            self.paste()
        elif sequence == self.CONF.get_shortcut(CONF_SECTION, 'clear'):
            self.clear()
        elif sequence == self.CONF.get_shortcut(
                CONF_SECTION, 'zoom in'):
            self.increase_font()
        elif sequence == self.CONF.get_shortcut(
                CONF_SECTION, 'zoom out'):
            self.decrease_font()
        else:
            super().keyPressEvent(event)
Esempio n. 18
0
    def __init__(self, package, parent=None):
        QSplitter.__init__(self, parent)
        self.setWindowTitle(_("Tests - %s module") % package.__name__)
        self.setWindowIcon(get_icon("%s.svg" % package.__name__,
                                    "guidata.svg"))

        test_package_name = "%s.tests" % package.__name__
        _temp = __import__(test_package_name)
        test_package = sys.modules[test_package_name]

        tests = get_tests(test_package)
        listwidget = QListWidget(self)
        listwidget.addItems([osp.basename(test.filename) for test in tests])

        self.properties = TestPropertiesWidget(self)

        self.addWidget(listwidget)
        self.addWidget(self.properties)

        self.properties.run_button.clicked.connect(
            lambda: tests[listwidget.currentRow()].run())
        self.properties.quit_button.clicked.connect(self.close)
        listwidget.currentRowChanged.connect(
            lambda row: self.properties.set_item(tests[row]))
        listwidget.itemActivated.connect(
            lambda: tests[listwidget.currentRow()].run())
        listwidget.setCurrentRow(0)

        QShortcut(QKeySequence("Escape"), self, self.close)

        self.setSizes([150, 1])
        self.setStretchFactor(1, 1)
        self.resize(QSize(950, 600))
        self.properties.set_item(tests[0])
Esempio n. 19
0
    def init_context_menu(self):
        """
        初始化右键菜单
        :return:
        """
        self.contextMenu = QMenu(self)
        self.openAction = self.contextMenu.addAction(self.tr('Open'))

        self.importAction = self.contextMenu.addAction(self.tr('Import'))
        self.importAction.setEnabled(False)

        self.new_file_or_folder_menu = QMenu(self.tr('New..'))
        self.contextMenu.addMenu(self.new_file_or_folder_menu)
        self.new_file_action = self.new_file_or_folder_menu.addAction(
            self.tr('File..'))
        self.new_python_file_action = self.new_file_or_folder_menu.addAction(
            self.tr('Python File'))
        self.new_folder_action = self.new_file_or_folder_menu.addAction(
            self.tr('Folder'))
        self.new_file_or_folder_menu.addSeparator()

        self.copyAction = self.contextMenu.addAction(self.tr("Copy"))
        self.pasteAction = self.contextMenu.addAction(self.tr("Paste"))
        self.pasteAction.setEnabled(False)

        self.renameAction = self.contextMenu.addAction(self.tr('Rename'))
        self.deleteAction = self.contextMenu.addAction(self.tr('Delete'))

        self.filterAction = self.contextMenu.addAction(self.tr('Filter'))
        self.copyPathAction = self.contextMenu.addAction(self.tr('Copy Path'))

        self.open_file_manager_action = self.contextMenu.addAction(
            self.tr('Open Explorer'))

        self.renameAction.setShortcut(QKeySequence('F2'))
        self.copyAction.setShortcut(QKeySequence('Ctrl+C'))
        self.pasteAction.setShortcut(QKeySequence('Ctrl+V'))
        self.deleteAction.setShortcut(QKeySequence('Delete'))

        self.rename_shortcut = QShortcut(QKeySequence('F2'),
                                         self,
                                         context=Qt.WidgetShortcut)
        self.copy_shortcut = QShortcut(QKeySequence.Copy,
                                       self,
                                       context=Qt.WidgetShortcut)
        self.paste_shortcut = QShortcut(QKeySequence.Paste,
                                        self,
                                        context=Qt.WidgetShortcut)
        self.delete_shortcut = QShortcut(QKeySequence('Delete'),
                                         self,
                                         context=Qt.WidgetShortcut)
        self.open_shortcut = QShortcut(QKeySequence('Return'),
                                       self,
                                       context=Qt.WidgetShortcut)
        self.goto_parent_path_shortcut = QShortcut(QKeySequence('Backspace'),
                                                   self,
                                                   context=Qt.WidgetShortcut)
Esempio n. 20
0
 def setupKeyboardShortcuts(self):
     for index, shortcut in enumerate(
         (sc.openControlPanelTab0, sc.openControlPanelTab1,
          sc.openControlPanelTab2, sc.openControlPanelTab3,
          sc.openControlPanelTab4, sc.openControlPanelTab5)):
         shortcut = QShortcut(QKeySequence(shortcut), self)
         shortcut.activated.connect(
             lambda index=index: self.tabs.setCurrentIndex(index))
Esempio n. 21
0
def new_shortcut(shortcut: str, scope: qw.QWidget,
                 slot: Callable) -> qw.QShortcut:
    parsed_keys = QKeySequence(shortcut, QKeySequence.PortableText)

    scoped_shortcut = qw.QShortcut(parsed_keys, scope)
    scoped_shortcut.setContext(Qt.WidgetWithChildrenShortcut)
    scoped_shortcut.activated.connect(slot)
    return scoped_shortcut
Esempio n. 22
0
 def context_menu_requested(self, event):
     """Popup context menu."""
     if self.fig:
         pos = QPoint(event.x(), event.y())
         context_menu = QMenu(self)
         context_menu.addAction(
             ima.icon('filesave'), _("Save plot as..."),
             lambda: self.sig_save_fig_requested.emit(),
             QKeySequence(CONF.get_shortcut('plots', 'save')))
         context_menu.addAction(
             ima.icon('editcopy'), _("Copy Image"), self.copy_figure,
             QKeySequence(CONF.get_shortcut('plots', 'copy')))
         context_menu.addAction(
             ima.icon('editclear'), _("Remove plot"),
             lambda: self.sig_clear_fig_requested.emit(),
             QKeySequence(CONF.get_shortcut('plots', 'close')))
         context_menu.popup(self.mapToGlobal(pos))
Esempio n. 23
0
def fixed_shortcut(keystr, parent, action):
    """
    DEPRECATED: This function will be removed in Spyder 4.0

    Define a fixed shortcut according to a keysequence string
    """
    sc = QShortcut(QKeySequence(keystr), parent, action)
    sc.setContext(Qt.WidgetWithChildrenShortcut)
    return sc
Esempio n. 24
0
    def __init__(self, parent):
        """Widget constructor."""
        SpyderPluginWidget.__init__(self, parent)
        self.tab_widget = None
        self.menu_actions = None
        self.port = select_port(default_port=8070)
        self.server = subprocess.Popen([
            sys.executable,
            osp.join(LOCATION, 'server', 'main.py'), '--port',
            str(self.port)
        ],
                                       stdout=subprocess.PIPE,
                                       stderr=subprocess.PIPE)
        time.sleep(0.5)
        self.main = parent

        self.terms = []
        self.untitled_num = 0
        self.initialize_plugin()

        layout = QVBoxLayout()
        new_term_btn = create_toolbutton(self,
                                         icon=ima.icon('project_expanded'),
                                         tip=_('Open a new terminal'),
                                         triggered=self.create_new_term)
        menu_btn = create_toolbutton(self,
                                     icon=ima.icon('tooloptions'),
                                     tip=_('Options'))
        self.menu = QMenu(self)
        menu_btn.setMenu(self.menu)
        menu_btn.setPopupMode(menu_btn.InstantPopup)
        add_actions(self.menu, self.menu_actions)
        # if self.get_option('first_time', True):
        # self.setup_shortcuts()
        # self.shortcuts = self.create_shortcuts()
        corner_widgets = {Qt.TopRightCorner: [new_term_btn, menu_btn]}
        self.tabwidget = Tabs(self,
                              menu=self.menu,
                              actions=self.menu_actions,
                              corner_widgets=corner_widgets)
        if hasattr(self.tabwidget, 'setDocumentMode') \
           and not sys.platform == 'darwin':
            # Don't set document mode to true on OSX because it generates
            # a crash when the console is detached from the main window
            # Fixes Issue 561
            self.tabwidget.setDocumentMode(True)
        self.tabwidget.currentChanged.connect(self.refresh_plugin)
        self.tabwidget.move_data.connect(self.move_tab)

        self.tabwidget.set_close_function(self.close_term)

        layout.addWidget(self.tabwidget)
        self.setLayout(layout)

        paste_shortcut = QShortcut(QKeySequence("Ctrl+Shift+T"), self,
                                   self.create_new_term)
        paste_shortcut.setContext(Qt.WidgetWithChildrenShortcut)
Esempio n. 25
0
 def context_menu_requested(self, event):
     """Popup context menu."""
     if self.fig:
         pos = QPoint(event.x(), event.y())
         context_menu = QMenu(self)
         context_menu.addAction(ima.icon('editcopy'), "Copy Image",
                                self.copy_figure,
                                QKeySequence(get_shortcut('plots', 'copy')))
         context_menu.popup(self.mapToGlobal(pos))
Esempio n. 26
0
    def __init__(self, parent):
        super().__init__(parent)

        # Create colored icon using theme
        self._image = QLabel()
        self._image.setObjectName("logo_silhouette")
        self._image.setMinimumSize(300, 300)
        self._label = QtWelcomeLabel(
            trans.
            _("Drag image(s) here to open\nor\nUse the menu shortcuts below:"))

        # Widget setup
        self.setAutoFillBackground(True)
        self.setAcceptDrops(True)
        self._image.setAlignment(Qt.AlignCenter)
        self._label.setAlignment(Qt.AlignCenter)

        # Layout
        text_layout = QVBoxLayout()
        text_layout.addWidget(self._label)

        # TODO: Use action manager for shortcut query and handling
        shortcut_layout = QFormLayout()
        sc = QKeySequence('Ctrl+O').toString(QKeySequence.NativeText)
        shortcut_layout.addRow(
            QtShortcutLabel(sc),
            QtShortcutLabel(trans._("open image(s)")),
        )
        sc = QKeySequence('Ctrl+Alt+/').toString(QKeySequence.NativeText)
        shortcut_layout.addRow(
            QtShortcutLabel(sc),
            QtShortcutLabel(trans._("show all key bindings")),
        )
        shortcut_layout.setSpacing(0)

        layout = QVBoxLayout()
        layout.addStretch()
        layout.setSpacing(30)
        layout.addWidget(self._image)
        layout.addLayout(text_layout)
        layout.addLayout(shortcut_layout)
        layout.addStretch()

        self.setLayout(layout)
Esempio n. 27
0
 def key_press(self, event: QKeyEvent):
     k = self.modifiers.get(event.modifiers())
     if k is not None:
         key_seq = QKeySequence(k + event.key())
         try:
             text = key_seq.toString()
             self.ctrl.setText(text)
         except:
             import traceback
             traceback.print_exc()
Esempio n. 28
0
    def __init__(self,
                 view_controller: 'Napping.ViewController',
                 parent: Optional[QObject] = None):
        # noinspection PyArgumentList
        super(NappingWidget, self).__init__(parent)
        self._view_controller = view_controller

        self._status_label = QLabel('Initializing', self)
        self._status_label.setAlignment(Qt.AlignCenter)

        self._prev_button = QPushButton(self)
        self._prev_button.setShortcut(QKeySequence(Qt.Key_Left))
        self._prev_button.setIcon(self.window().style().standardIcon(
            QStyle.SP_ArrowBack))

        self._next_button = QPushButton(self)
        self._next_button.setShortcut(QKeySequence(Qt.Key_Right))
        self._next_button.setIcon(self.window().style().standardIcon(
            QStyle.SP_ArrowForward))

        # noinspection PyUnusedLocal
        # noinspection PyUnresolvedReferences
        @self._prev_button.clicked.connect
        def on_prev_button_clicked(checked=False):
            view_controller.controller.show_prev()

        # noinspection PyUnusedLocal
        # noinspection PyUnresolvedReferences
        @self._next_button.clicked.connect
        def on_next_button_clicked(checked=False):
            view_controller.controller.show_next()

        layout = QHBoxLayout()
        layout.addStretch()
        # noinspection PyArgumentList
        layout.addWidget(self._prev_button)
        # noinspection PyArgumentList
        layout.addWidget(self._status_label)
        # noinspection PyArgumentList
        layout.addWidget(self._next_button)
        layout.addStretch()
        self.setLayout(layout)
Esempio n. 29
0
def _config_shortcut(action, context, name, keystr, parent):
    """
    Create a Shortcut namedtuple for a widget.

    The data contained in this tuple will be registered in our shortcuts
    preferences page.
    """
    qsc = QShortcut(QKeySequence(keystr), parent, action)
    qsc.setContext(Qt.WidgetWithChildrenShortcut)
    sc = Shortcut(data=(qsc, context, name))
    return sc
Esempio n. 30
0
    def __init__(self):
        QPlainTextEdit.__init__(self)
        self.setWordWrapMode(QTextOption.NoWrap)
        self.setFont(QFont("monospace", 10))
        self.setCursorWidth(2)
        self.installEventFilter(self)

        self.completer = QCompleter(self)
        self.completer.setWidget(self)
        self.completer.setCaseSensitivity(Qt.CaseInsensitive)
        self.completer.activated.connect(self.insertCompletion)

        auto_complete = QShortcut(QKeySequence("Ctrl+Space"), self)
        auto_complete.activated.connect(self.activateCompleter)

        copy_line = QShortcut(QKeySequence("Ctrl+D"), self)
        copy_line.activated.connect(self.duplicateLine)

        select_fragment = QShortcut(QKeySequence("Ctrl+J"), self)
        select_fragment.activated.connect(self.selectFragment)