def validate_sequence(self): """Provide additional checks for accepting or rejecting shortcuts.""" if self.invalid_key_flag: self.update_warning(warning_type=INVALID_KEY) return for mod in MODIFIERS: non_mod = set(self.key_non_modifiers) non_mod.discard(mod) if mod in self.key_non_modifiers: self.key_non_modifiers.remove(mod) self.key_modifiers = self.key_modifiers - non_mod while u'' in self.key_text: self.key_text.remove(u'') self.key_text = [k.upper() for k in self.key_text] # Fix Backtab, Tab issue if os.name == 'nt': if Qt.Key_Backtab in self.key_non_modifiers: idx = self.key_non_modifiers.index(Qt.Key_Backtab) self.key_non_modifiers[idx] = Qt.Key_Tab if len(self.key_modifiers) == 0: # Filter single key allowed if self.key_non_modifiers[0] not in VALID_SINGLE_KEYS: return # Filter elif len(self.key_non_modifiers) > 1: return # QKeySequence accepts a maximum of 4 different sequences if len(self.keys) > 4: # Update warning self.update_warning(warning_type=SEQUENCE_LENGTH) return keys = [] for i in range(len(self.keys)): key_seq = 0 for m in self.key_modifiers: key_seq += MODIFIERS[m] key_seq += self.key_non_modifiers[i] keys.append(key_seq) sequence = QKeySequence(*keys) self.set_sequence(sequence.toString())
def add_shortcut_to_tooltip(action, context, name): """Add the shortcut associated with a given action to its tooltip""" if not hasattr(action, '_tooltip_backup'): # We store the original tooltip of the action without its associated # shortcut so that we can update the tooltip properly if shortcuts # are changed by the user over the course of the current session. # See spyder-ide/spyder#10726. action._tooltip_backup = action.toolTip() try: # Some shortcuts might not be assigned so we need to catch the error shortcut = CONF.get_shortcut(context=context, name=name) except (configparser.NoSectionError, configparser.NoOptionError): shortcut = None if shortcut: keyseq = QKeySequence(shortcut) # See: spyder-ide/spyder#12168 string = keyseq.toString(QKeySequence.NativeText) action.setToolTip(u'{0} ({1})'.format(action._tooltip_backup, string))
def add_actions_to_context_menu(self, menu): """Add actions to IPython widget context menu""" inspect_action = create_action( self, _("Inspect current object"), QKeySequence(CONF.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(CONF.get_shortcut('console', 'clear line')), triggered=self.clear_line) reset_namespace_action = create_action(self, _("Remove all variables"), QKeySequence( CONF.get_shortcut( 'ipython_console', 'reset namespace')), icon=ima.icon('editdelete'), triggered=self.reset_namespace) clear_console_action = create_action( self, _("Clear console"), QKeySequence(CONF.get_shortcut('console', 'clear shell')), 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
def keyPressEvent(self, event): """Override Qt method.""" key = event.key() modifier = event.modifiers() if modifier != Qt.NoModifier: return if not key or key == Qt.Key_unknown: return key_str = QKeySequence(key).toString() self.viewer.setText(key_str)
def __init__(self, parent, term_url='http://127.0.0.1:8070'): """Webview main constructor.""" WebView.__init__(self, 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)
def __init__(self, *args, **kwargs): super(DebuggableMenuBar, self).__init__(*args, **kwargs) self.debugshortcut = QShortcut(QKeySequence("Ctrl+Return"), self, self.showDebugMenu, context=Qt.ApplicationShortcut) self._debugmenu = QMenu("Debugging") self._debugmenu.addAction("Debug widget", self.startDebugging) self.mousedebugger = MouseDebugger()
def config_shortcut(action, context, name, parent): """ Create a Shortcut namedtuple for a widget The data contained in this tuple will be registered in our shortcuts preferences page """ keystr = get_shortcut(context, name) qsc = QShortcut(QKeySequence(keystr), parent, action) qsc.setContext(Qt.WidgetWithChildrenShortcut) sc = Shortcut(data=(qsc, context, name)) return sc
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(get_shortcut('console', 'Clear line')), icon=ima.icon('editdelete'), tip=_("Clear line"), triggered=self.clear_line) clear_action = create_action(self, _("Clear shell"), QKeySequence(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))
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)
def __init__(self): QPlainTextEdit.__init__(self) self.setWordWrapMode(QTextOption.NoWrap) self.setFont(QFont("monospace", 10)) self.setCursorWidth(2) self.installEventFilter(self) self.cursorPositionChanged.connect(self.showHelp) 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)
def _add_menubar(self): self.main_menu = self._qt_window.menuBar() # Menubar shortcuts are only active when the menubar is visible. # Therefore, we set a global shortcut not associated with the menubar # to toggle visibility, *but*, in order to not shadow the menubar # shortcut, we disable it, and only enable it when the menubar is # hidden. See this stackoverflow link for details: # https://stackoverflow.com/questions/50537642/how-to-keep-the-shortcuts-of-a-hidden-widget-in-pyqt5 self._main_menu_shortcut = QShortcut(QKeySequence('Ctrl+M'), self._qt_window) self._main_menu_shortcut.activated.connect( self._toggle_menubar_visible) self._main_menu_shortcut.setEnabled(False)
def register_plugin(self): """Register plugin in Spyder's main window.""" try: # Spyder 3 compatibility super(Vim, self).register_plugin() except NotImplementedError: pass self.focus_changed.connect(self.main.plugin_focus_changed) self.vim_cmd.editor_widget.layout().addWidget(self.vim_cmd) sc = QShortcut(QKeySequence("Esc"), self.vim_cmd.editor_widget.editorsplitter, self.vim_cmd.commandline.setFocus) sc.setContext(Qt.WidgetWithChildrenShortcut)
def addMenuActions(self): copyText = QAction(self) copyText.setText(config.thisTranslation["context1_copy"]) copyText.triggered.connect(self.copySelectedText) self.addAction(copyText) runAsCommandLine = QAction(self) runAsCommandLine.setText(config.thisTranslation["context1_command"]) runAsCommandLine.triggered.connect(self.runAsCommand) self.addAction(runAsCommandLine) if hasattr(config, "macroIsRunning") and config.macroIsRunning: spaceBar = QAction(self) spaceBar.setShortcut(QKeySequence(" ")) spaceBar.triggered.connect(self.spaceBarPressed) self.addAction(spaceBar) escKey = QAction(self) escKey.setShortcut(QKeySequence(Qt.Key_Escape)) escKey.triggered.connect(self.escKeyPressed) self.addAction(escKey) qKey = QAction(self) qKey.setShortcut(QKeySequence(Qt.Key_Q)) qKey.triggered.connect(self.qKeyPressed) self.addAction(qKey) escKey = QAction(self) escKey.setText(config.thisTranslation["menu1_fullScreen"]) escKey.setShortcut(QKeySequence(Qt.Key_Escape)) escKey.triggered.connect(self.escKeyPressed) self.addAction(escKey) qKey = QAction(self) qKey.setText(config.thisTranslation["close"]) qKey.setShortcut(QKeySequence("Alt+Q")) qKey.triggered.connect(self.qKeyPressed) self.addAction(qKey)
def create_toggle_view_action(self): """Associate a toggle view action with each plugin""" title = self.get_plugin_title() if self.CONF_SECTION == 'editor': title = _('Editor') if self.shortcut is not None: action = create_action(self, title, toggled=lambda checked: self.toggle_view(checked), shortcut=QKeySequence(self.shortcut), context=Qt.WidgetShortcut) else: action = create_action(self, title, toggled=lambda checked: self.toggle_view(checked)) self.toggle_view_action = action
def getContextMenus(self, event=None): """Get context menus. Args: event: DESCRIPTION. Defaults to None. """ if self.menu is None: self.menu = QMenu() self.menu.setTitle(self.name + " options..") view_all = QAction("View all", self.menu) view_all.triggered.connect(self.view_all) self.menu.addAction(view_all) self.menu.view_all = view_all toggle_aspect_mode = QAction("Locked aspect", self.menu, checkable=True) toggle_aspect_mode.triggered.connect(self.toggle_aspect_mode) toggle_aspect_mode.setChecked(True) self.menu.addAction(toggle_aspect_mode) self.menu.toggle_aspect_mode = toggle_aspect_mode toggle_click_mode = QAction( "Mouse panmode", self.menu, shortcut=QKeySequence("Shift+S"), checkable=True, ) toggle_click_mode.triggered.connect(self.toggle_mouse_mode) self.menu.addAction(toggle_click_mode) self.menu.toggle_mode = toggle_click_mode export_view = QAction("Export View", self.menu) export_view.setToolTip("Axis와 Marker를 포함한 화면을 캡쳐한다.") export_view.triggered.connect(self.export_view_clicked) self.menu.addAction(export_view) export_img = QAction("Export data as png", self.menu) export_img.setToolTip("Imagesc의 Data 원본을 Image 파일로 저장한다.") export_img.triggered.connect(self.export_data_as_img_clicked) self.menu.addAction(export_img) if self.view.vb.state["mouseMode"] == self.view.vb.PanMode: self.menu.toggle_mode.setChecked(True) else: self.menu.toggle_mode.setChecked(False) return self.menu
def get_options_menu(self): """Return options menu""" restart_action = create_action(self, _("Restart kernel"), shortcut=QKeySequence("Ctrl+."), icon=ima.icon('restart'), triggered=self.restart_kernel, context=Qt.WidgetWithChildrenShortcut) # Main menu if self.menu_actions is not None: actions = [restart_action, None] + self.menu_actions else: actions = [restart_action] return actions
def __connect__(self): """ Connects events to event handlers. :return: """ self.ui.action_AddDay.triggered.connect(self.add_new_day) self.ui.action_Exit.triggered.connect(self.close) self.ui.list_days.itemClicked.connect(self.activated_details) self.ui.pushButton_addRow.clicked.connect(self.add_entry_row) self.ui.pushButton_save.clicked.connect(self.save_entity_table) self.ui.pushButton_addBookRow.clicked.connect(self.add_booking_row) self.ui.pushButton_saveBookRow.clicked.connect(self.save_booking_table) self.ui.pushButton_deleteEntityRow.clicked.connect(self.delete_entry_row) self.ui.pushButton_deleteBookingRow.clicked.connect(self.delete_booking_row) self.ui.pushButton_copyTime.clicked.connect(self.copy_entries_to_bookings) self.ui.pushButton_rowUp.clicked.connect(self.shift_up_entry_row) self.ui.pushButton_rowDown.clicked.connect(self.shift_down_entry_row) self.ui.pushButton_bookingRowUp.clicked.connect(self.shift_up_booking_row) self.ui.pushButton_bookingRowDown.clicked.connect(self.shift_down_booking_row) self.ui.tabWidget_Details.currentChanged.connect(self.__set_selected_tab__) QShortcut(QKeySequence("Alt+a"), self, self.hit_alt_a) QShortcut(QKeySequence("Alt+d"), self, self.hit_alt_d) QShortcut(QKeySequence("Alt+s"), self, self.hit_alt_s)
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', QKeySequence.PortableText).toString( QKeySequence.NativeText) shortcut_layout.addRow( QtShortcutLabel(sc), QtShortcutLabel(trans._("open image(s)")), ) self._shortcut_label = QtShortcutLabel("") shortcut_layout.addRow( self._shortcut_label, 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) self._show_shortcuts_updated() action_manager.events.shorcut_changed.connect( self._show_shortcuts_updated)
def check_conflicts(self): """Check shortcuts for conflicts.""" conflicts = [] if len(self._qsequences) == 0: return conflicts new_qsequence = self.new_qsequence for shortcut in self.shortcuts: shortcut_qsequence = QKeySequence.fromString(str(shortcut.key)) if shortcut_qsequence.isEmpty(): continue if (shortcut.context, shortcut.name) == (self.context, self.name): continue if shortcut.context in [self.context, '_'] or self.context == '_': if (shortcut_qsequence.matches(new_qsequence) or new_qsequence.matches(shortcut_qsequence)): conflicts.append(shortcut) return conflicts
def event_startup(self): from jupyter_tabwidget import ConsoleTabWidget self.set_busy(True) self._jupyter_console = ConsoleTabWidget(self.main_window) self._dock_widget = QDockWidget(u'Console', self.main_window) self._dock_widget.setObjectName(u'JupyterConsole') self._dock_widget.setWidget(self._jupyter_console) self._dock_widget.closeEvent = self._on_close_event self.main_window.addDockWidget(Qt.BottomDockWidgetArea, self._dock_widget) self._set_visible(cfg.jupyter_visible) self._shortcut_focus = QShortcut(QKeySequence( cfg.jupyter_focus_shortcut), self.main_window, self._focus, context=Qt.ApplicationShortcut) self.set_busy(False)
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(self._ALLOWED_AREAS) dock.setFeatures(self._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 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)
def makeAction(parent, descr, menutext, slot, icon=None, key=None, checkable=False): a = QAction(parent) a.setText(menutext) a.setStatusTip(descr) a.setToolTip(textwrap.fill(descr, 25)) if slot: a.triggered.connect(slot) if icon: a.setIcon(getIcon(icon)) if key: a.setShortcut(QKeySequence(key)) if checkable: a.setCheckable(True) return a
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 ''
def _hide_shortcuts(self, menu): """ Hide action shortcuts in menu. Parameters ---------- menu: SpyderMenu Instance of a spyder menu. """ menu_actions = menu.actions() for action in menu_actions: if getattr(action, '_shown_shortcut', False): # This is a SpyderAction if action._shown_shortcut is not None: action.setShortcut(QKeySequence()) elif action.menu() is not None: # This is submenu, so we need to call this again self._hide_shortcuts(action.menu()) else: # We don't need to do anything for other elements continue
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: 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 if column == CONTEXT: if len(self.context_rich_text) > 0: text = self.context_rich_text[row] else: text = shortcut.context text = '<p style="color:{0}">{1}</p>'.format(color, text) return to_qvariant(text) elif column == NAME: 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()
def __init__(self, parent, model): # check model if not isinstance(model, DataArrayModel): raise TypeError( "Expected model of type {}. Received {} instead".format( DataArrayModel.__name__, type(model).__name__)) AbstractView.__init__(self, parent, model, RIGHT, BOTTOM) self.context_menu = self.setup_context_menu() # TODO: find a cleaner way to do this # For some reason the shortcuts in the context menu are not available if the widget does not have the focus, # EVEN when using action.setShortcutContext(Qt.ApplicationShortcut) (or Qt.WindowShortcut) so we redefine them # here. I was also unable to get the function an action.triggered is connected to, so I couldn't do this via # a loop on self.context_menu.actions. shortcuts = [(keybinding('Copy'), self.parent().copy), (QKeySequence("Ctrl+E"), self.parent().to_excel), (keybinding('Paste'), self.parent().paste), (keybinding('Print'), self.parent().plot)] for key_seq, target in shortcuts: shortcut = QShortcut(key_seq, self) shortcut.activated.connect(target)
def keyPressEvent(self, event): """Reimplement Qt method""" # comparing with the keysequence and not with event directly as we # did before because that only seems to work for shortcut # defined using QKeySequence.StandardKey, which is not the case for # Ctrl + E keyseq = QKeySequence(event.modifiers() | event.key()) if keyseq == QKeySequence.Copy: self.copy() elif keyseq == QKeySequence.Paste: self.paste() elif keyseq == QKeySequence.Print: self.parent().plot() elif keyseq == "Ctrl+E": self.to_excel() # allow to start editing cells by pressing Enter elif event.key() == Qt.Key_Return and not self.model().readonly: index = self.currentIndex() if self.itemDelegate(index).editor_count == 0: self.edit(index) else: QTableView.keyPressEvent(self, event)
def create_action(parent, text, on_triggered=None, shortcut=None, shortcut_context=None, icon_name=None, shortcut_visible_in_context_menu=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. :param shortcut_visible_in_context_menu: Qt 5.10 decided that all QMenus that are NOT inside a QMenuBar are context menus, and are styled as such. By default keyboard shortcuts are NOT shown on context menus. Set this to True to show them. :return: A new QAction object """ from ...icons import get_icon # noqa 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)) # shortcuts in context menus option is only available after Qt 5.10 if hasattr(action, 'setShortcutVisibleInContextMenu') and shortcut_visible_in_context_menu: action.setShortcutVisibleInContextMenu(shortcut_visible_in_context_menu) return action
def __init__(self, parent=None, table_view: 'PMTableView' = None): super().__init__(parent) self.setLayout(QVBoxLayout()) self.top_layout = QHBoxLayout() self.layout().addLayout(self.top_layout) self.table_view = table_view self.slice_input = QLineEdit() self.help_button = QPushButton(QCoreApplication.translate('PMGTableViewer','Help')) self.slice_refresh_button = QPushButton(QCoreApplication.translate('PMGTableViewer','Slice')) self.save_change_button = QPushButton(QCoreApplication.translate('PMGTableViewer','Save')) self.goto_cell_button = QPushButton(QCoreApplication.translate('PMGTableViewer','Go To Cell')) self.save_change_button.clicked.connect(self.on_save) self.slice_refresh_button.clicked.connect(self.slice) self.help_button.clicked.connect(self.on_help) self.goto_cell_button.clicked.connect(self.on_goto_cell) self.slice_input.hide() self.slice_refresh_button.hide() self.table_view.signal_need_save.connect(self.signal_need_save.emit) self.signal_need_save.connect(self.on_signal_need_save) self.top_layout.addWidget(self.goto_cell_button) self.top_layout.addWidget(self.save_change_button) self.top_layout.addWidget(self.help_button) self.top_layout.addWidget(self.slice_input) self.top_layout.addWidget(self.slice_refresh_button) self.top_layout.addItem(QSpacerItem(0, 0, QSizePolicy.Expanding, QSizePolicy.Minimum)) if table_view is not None: self.layout().addWidget(self.table_view) self.shortcut_save = QShortcut(QKeySequence.Save, self.table_view, context=Qt.WidgetShortcut) self.shortcut_save.activated.connect(self.on_save) self.shortcut_goto = QShortcut(QKeySequence('Ctrl+G'), self.table_view, context=Qt.WidgetShortcut) self.shortcut_goto.activated.connect(self.on_goto_cell)
def setup_ui(self): """Initialize widgets.""" def switch_style(i): view = self.landscape_view if self.view_mode == MainApp.LANDSCAPE else self.portrait_view self.style_changed.emit(self.styles[i]) view.selected_style = self.styles[i] for i in range(min(len(self.styles), len(settings.STYLE_SHORTCUTS))): QShortcut(QKeySequence(settings.STYLE_SHORTCUTS[i]), self, lambda x=i: switch_style(x)) self.landscape_view = LandscapeView(self.styles) self.landscape_view.style_changed.connect(self.style_button_clicked) self.landscape_view.toggle_fullscreen_signal.connect( self.toggle_fullscreen) self.landscape_view.quality_changed.connect(self.quality_choice) self.portrait_view = PortraitView(self.styles) self.portrait_view.style_changed.connect(self.style_button_clicked) self.portrait_view.toggle_fullscreen_signal.connect( self.toggle_fullscreen) self.portrait_view.quality_changed.connect(self.quality_choice) self.main_layout = QStackedLayout() self.main_layout.addWidget(self.landscape_view) self.main_layout.addWidget(self.portrait_view) self.setLayout(self.main_layout) self.view_mode = MainApp.LANDSCAPE self.setStyleSheet('background-color:black;' 'font-family: Arial;' 'font-style: normal;' 'font-size: 12pt;' 'font-weight: bold;' 'color:white;') self.setWindowTitle('Stylize')
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()
def keybinding(attr): """Return keybinding""" ks = getattr(QKeySequence, attr) return from_qvariant(QKeySequence.keyBindings(ks)[0], str)