def createButton(self, button, propertyDict = dict()): """ Creates the buttons according to the user size definition button: Button name propertyDict: optional dict parameters that may contain other properties to button, such as color, tooltip and custom category """ pushButton = QtGui.QPushButton(button) keys = propertyDict.keys() styleSheet = '' if 'buttonColor' in keys: r, g, b, a = propertyDict['buttonColor'].split(',') styleSheet += "background-color:rgba({0},{1},{2},{3});".format(r, g, b, a) if 'buttonToolTip' in keys: pushButton.setToolTip(propertyDict['buttonToolTip']) if 'buttonShortcut' in keys: keySequence = QKeySequence(propertyDict['buttonShortcut']) pushButton.setText('{0} [{1}]'.format(button, keySequence.toString(format = QKeySequence.NativeText))) pushButton.setShortcut(keySequence) pushButton.clicked.connect(self.reclassify) pushButton.toggled.connect(self.acquire) if self.size == 0: pushButton.setMinimumSize(100, 25) styleSheet += 'font-size:12px;' elif self.size == 1: pushButton.setMinimumSize(100, 40) styleSheet += 'font-size:20px;' elif self.size == 2: pushButton.setMinimumSize(100, 80) styleSheet += 'font-size:30px;' pushButton.setStyleSheet(styleSheet) self.buttons.append(pushButton) return pushButton
def removeShortcut(action, key): """Removes matching QKeySequence from the list of the action.""" key = QKeySequence(key) shortcuts = action.shortcuts() for s in action.shortcuts(): if key.matches(s) or s.matches(key): shortcuts.remove(s) action.setShortcuts(shortcuts)
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)
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 )
def create_actions(self): new_tab_action = QAction('&New Tab', self) new_tab_action.setShortcuts(QKeySequence.AddTab) self.connect(new_tab_action, SIGNAL('triggered()'), self.new_tab) self.new_tab_action = new_tab_action close_tab_action = QAction('&Close Tab', self) close_tab_action.setShortcuts(QKeySequence.Close) self.connect(close_tab_action, SIGNAL('triggered()'), self.close_tab) self.close_tab_action = close_tab_action open_action = QAction('&Open...', self) open_action.setShortcuts(QKeySequence.Open) self.connect(open_action, SIGNAL('triggered()'), self.open_file) self.open_action = open_action save_as_action = QAction('Save &As...', self) save_as_action.setShortcuts(QKeySequence.SaveAs) self.connect(save_as_action, SIGNAL('triggered()'), self.save_as_file) self.save_as_action = save_as_action exit_action = QAction('E&xit', self) exit_action.setMenuRole(QAction.QuitRole) self.connect(exit_action, SIGNAL('triggered()'), self, SLOT('close()')) self.exit_action = exit_action next_tab_action = QAction('Next Tab', self) bindings = QKeySequence.keyBindings(QKeySequence.NextChild) if sys.platform == 'darwin': bindings.append('Meta+PgDown') bindings.append('Meta+Tab') else: bindings.append('Ctrl+PgDown') next_tab_action.setShortcuts(bindings) self.connect(next_tab_action, SIGNAL('triggered()'), self.focus_next_tab); self.addAction(next_tab_action) previous_tab_action = QAction('Previous Tab', self) bindings = QKeySequence.keyBindings(QKeySequence.PreviousChild) if sys.platform == 'darwin': bindings.append('Meta+PgUp') bindings.append('Meta+Shift+Tab') else: bindings.append('Ctrl+PgUp') previous_tab_action.setShortcuts(bindings) self.connect(previous_tab_action, SIGNAL('triggered()'), self.focus_previous_tab); self.addAction(previous_tab_action)
def keys(self, pattern, text, native=False, blur=False): """Simulate typing by focusing on elements that match the pattern and triggering key events. If native is True then will use GUI key event simulation, else JavaScript. If blur is True then will blur focus at the end of typing. Returns the number of elements matched. """ es = self.find(pattern) for e in es: if native: key_map = { '\t': Qt.Key_Tab, '\n': Qt.Key_Enter, 'DOWN': Qt.Key_Down, 'UP': Qt.Key_Up } self.click_by_gui_simulation(e) self.wait(0.1) for c in text: key = key_map.get(c, QKeySequence(c)[0]) press = QKeyEvent(QEvent.KeyPress, key, Qt.NoModifier) release = QKeyEvent(QEvent.KeyRelease, key, Qt.NoModifier) QApplication.postEvent(self, press) QApplication.postEvent(self, release) else: #e.evaluateJavaScript("this.focus()") #self.click_by_user_event_simulation(e) self.fill(pattern, text, es=[e]) for event_name in ('focus', 'keydown', 'change', 'keyup', 'keypress'): self.trigger_js_event(e, event_name) if blur: e.evaluateJavaScript("this.blur()") return len(es)
def clear(self): """Empties the displayed shortcut.""" if self.button.isRecording(): self.button.cancelRecording() if not self.button.keySequence().isEmpty(): self.button.setKeySequence(QKeySequence()) self.keySequenceChanged.emit(self._num)
def createActions(self, parent=None): self.lyrics_hyphenate = QAction(parent) self.lyrics_dehyphenate = QAction(parent) self.lyrics_copy_dehyphenated = QAction(parent) self.lyrics_hyphenate.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_L))
def install(self): """ currently only can create menu entries and sets shortcuts """ if self.menu: mh = MenuHooks() menu = mh.findMenu(self.menu) if not menu: menu = mh.createMenu(self.menu) mh.appendMenu(menu) if self.separator_before: mh.appendSeparator(menu) self.action = mh.appendItem(menu, self.title, lambda: self.run()) if self.separator_after: mh.appendSeparator(menu) if self.icon: icon_filename = os.path.join(os.path.dirname(self.filename), self.icon) if os.path.exists(icon_filename): self.action.setIcon(QIcon(icon_filename)) else: print >> sys.stderr, "Icon %r not found" % icon_filename if self.shortcut: print >> sys.stdout, "Shortcut %r." % self.shortcut self.action.setShortcut(QKeySequence(self.shortcut))
def __init__(self, parent=None): super(SearchMenu, self).__init__(parent) self.ui = Ui_SearchMenu() self.ui.setupUi(self) #self.setAttribute(QtCore.Qt.WA_DeleteOnClose) # Feels herpy. #self.ui.buttonBox.accepted.connect(self.open_clicked.emit) self.ui.shortcutFind = QShortcut(QKeySequence("Ctrl+F"), self) self.ui.shortcutFind.activated.connect(self.highlight_query) self.ui.btnFilterSelAll.clicked.connect(lambda: self.filterSetAll(True)) self.ui.btnFilterSelNone.clicked.connect(lambda: self.filterSetAll(False)) # Unchecked is easier to work with, # since it searches everything if nothing's given. self.filterSetAll(False) self.ui.treeResults.setHeaderLabel("Results (0)") self.ui.actionCopyPath = QtGui.QAction("Copy path", None, triggered = self.copyPath) self.ui.treeResults.addAction(self.ui.actionCopyPath) self.transHighlighter = KeywordHighlighter(self.ui.txtTranslated.document()) self.origHighlighter = KeywordHighlighter(self.ui.txtOriginal.document()) self.commHighlighter = KeywordHighlighter(self.ui.txtComments.document()) self.re_flags = re.UNICODE | re.MULTILINE
def createActions(self, parent=None): self.help_back = QAction(parent) self.help_forward = QAction(parent) self.help_home = QAction(parent) self.help_print = QAction(parent) self.help_lilypond_doc = QAction(parent) self.help_lilypond_context = QAction(parent) self.help_back.setIcon(icons.get("go-previous")) self.help_forward.setIcon(icons.get("go-next")) self.help_home.setIcon(icons.get("go-home")) self.help_lilypond_doc.setIcon(icons.get("lilypond-run")) self.help_print.setIcon(icons.get("document-print")) self.help_lilypond_doc.setShortcut(QKeySequence("F9")) self.help_lilypond_context.setShortcut(QKeySequence("Shift+F9"))
def keyPressEvent(self, e): if e.type() == QEvent.KeyPress: key = e.key() if key == Qt.Key_unknown: return if key == Qt.Key_Escape or key == Qt.Key_Backspace: self.setText("") return if (key == Qt.Key_Control or key == Qt.Key_Shift or key == Qt.Key_Alt or key == Qt.Key_Meta): return modifiers = e.modifiers() if modifiers & Qt.ControlModifier: key += Qt.CTRL if modifiers & Qt.ShiftModifier: key += Qt.SHIFT if modifiers & Qt.AltModifier: key += Qt.ALT if modifiers & Qt.MetaModifier: key += Qt.META self.setKeySequence(QKeySequence(key))
def setupMenu(self): menu = self.form.menuEdit menu.addSeparator() a = menu.addAction('Create Duplicate') a.setShortcut(QKeySequence("Ctrl+Alt+C")) self.connect(a, SIGNAL("triggered()"), lambda b=self: onCreateDuplicate(b))
def __init__(self, parent=None): super(SearchMenu, self).__init__(parent) self.ui = Ui_SearchMenu() self.ui.setupUi(self) self.ui.shortcutFind = QShortcut(QKeySequence("Ctrl+F"), self) self.ui.shortcutFind.activated.connect(self.select_query) self.ui.txtQuery.setCompleter(None) self.ui.txtQuery.setMaxCount(25) self.ui.txtQuery.setMaxVisibleItems(25) self.ui.txtQuery.setInsertPolicy(QtGui.QComboBox.NoInsert) self.ui.txtQuery.view().setTextElideMode(Qt.Qt.ElideNone) self.ui.txtQuery.currentIndexChanged.connect(self.select_query) self.ui.btnFilterSelAll.clicked.connect(lambda: self.filterSetAll(True)) self.ui.btnFilterSelNone.clicked.connect(lambda: self.filterSetAll(False)) # Unchecked is easier to work with, # since it searches everything if nothing's given. self.filterSetAll(False) self.ui.treeResults.setHeaderLabel("Results (0)") self.ui.actionCopyPath = QtGui.QAction("Copy path", None, triggered = self.copyPath) self.ui.treeResults.addAction(self.ui.actionCopyPath) self.query_re = None self.re_flags = re.UNICODE | re.MULTILINE
def __init__(self, parent, cls, zid): """ Arguments: parent: parent widget cls: the Class this quiz belongs to zid: the Quiz to display results for """ QDialog.__init__(self) self.form = Ui_Dialog() self.form.setupUi(self) self.parent = parent self.cls = cls self.zid = zid self.form.closeButton.clicked.connect(self.reject) self.form.viewQuizButton.clicked.connect(self.onViewQuiz) self.form.deleteResultsButton.clicked.connect(self.onDeleteResults) self.tableModel = AnswersTableModel(self) self.form.stuAnswersTable.setModel(self.tableModel) self.form.studentsTable.itemSelectionChanged.connect( self.displayStudent) qlShortcut = QShortcut(QKeySequence("Alt+L"), self.form.studentsTable) qlShortcut.connect(qlShortcut, QtCore.SIGNAL("activated()"), self.form.studentsTable.setFocus) # initialize lists self.setupStudentList() self.setupSummaryData() self.form.studentsTable.setCurrentRow(0) self.displayStudent()
def filter(self, filterString: str, item: QTreeWidgetItem) -> bool: visible = (filterString == "") columnCount = item.columnCount() for i in range(columnCount): if not visible: break text = item.text(i) if HostOsInfo.isMacHost(): # accept e.g. Cmd+E in the filter. the text shows special fancy characters for Cmd if i == columnCount - 1: key = QKeySequence.fromString(text, QKeySequence.NativeText) if not key.isEmpty(): text = key.toString(QKeySequence.PortableText) text.replace("Ctrl", "Cmd") text.replace("Meta", "Ctrl") text.replace("Alt", "Opt") if filterString.upper() in text.upper(): # case insensitive visible = True childCount = item.childCount() if childCount > 0: # force visibility if this item matches leafFilterString = "" if visible else filterString for i in range(childCount): citem = item.child(i) # QTreeWidgetItem if not filter(leafFilterString, citem): visible = True item.setHidden(not visible) return not visible
def __init__(self, parentObject, windowTitle, windowIcon=QIcon(), shortcut=None): QDockWidget.__init__(self, parentObject) self._showAction = None self.setObjectName(str(self.__class__)) self.setWindowTitle(windowTitle) self.setFeatures(self.features() & (~QDockWidget.DockWidgetFloatable)) if not windowIcon.isNull(): self.setWindowIcon(windowIcon) if shortcut is not None: self.showAction().setShortcut(shortcut) self._titleBar = _TitleBar(self) self.setTitleBarWidget(self._titleBar) if shortcut is not None: toolTip = "Move focus with <b>%s</b>,<br/>close with <b>Esc</b>" % shortcut else: toolTip = "Close with <b>Esc</b>" self._titleBar.setToolTip(toolTip) self._closeShortcut = QShortcut(QKeySequence("Esc"), self) self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut) self._closeShortcut.activated.connect(self._close)
def textEffectMenu(self): format = self.currentCharFormat() menu = QMenu("Text Effect") for text, shortcut, data, checked in ( ("&Bold", "Ctrl+B", RichTextLineEdit.Bold, self.fontWeight() > QFont.Normal), ("&Italic", "Ctrl+I", RichTextLineEdit.Italic, self.fontItalic()), ("Strike &out", None, RichTextLineEdit.StrikeOut, format.fontStrikeOut()), ("&Underline", "Ctrl+U", RichTextLineEdit.Underline, self.fontUnderline()), ("&Monospaced", None, RichTextLineEdit.Monospaced, format.fontFamily() == self.monofamily), ("&Serifed", None, RichTextLineEdit.Serif, format.fontFamily() == self.seriffamily), ("S&ans Serif", None, RichTextLineEdit.Sans, format.fontFamily() == self.sansfamily), ("&No super or subscript", None, RichTextLineEdit.NoSuperOrSubscript, format.verticalAlignment() == QTextCharFormat.AlignNormal), ("Su&perscript", None, RichTextLineEdit.Superscript, format.verticalAlignment() == QTextCharFormat.AlignSuperScript), ("Subs&cript", None, RichTextLineEdit.Subscript, format.verticalAlignment() == QTextCharFormat.AlignSubScript)): action = menu.addAction(text, self.setTextEffect) if shortcut is not None: action.setShortcut(QKeySequence(shortcut)) action.setData(QVariant(data)) action.setCheckable(True) action.setChecked(checked) self.ensureCursorVisible() menu.exec_(self.viewport().mapToGlobal(self.cursorRect().center()))
def _firstLetterShortcut(self, button, text): """ Provide first-letter only shortcuts (not Alt+first letter which is already present because of the & before letters) for a button. button - One of self.buttonBox.[Discard/Cancel/Save] text - Text for this button's label. The letter following the & will have a shortcut created for it. Return value: the shortcut for the given button. """ # Set the text of the button, which automatically provides an Alt+letter # shortcut. self.buttonBox.button(button).setText(self.tr(text)) # Get the letter after the ampersand (there should be exactly one # ampersand in the string). assert text.count('&') == 1 letter = text[text.index('&') + 1] # Create a first-letter only shortcut, which clicks the button when # the letter is typed. shortcut = QShortcut(QKeySequence(letter), self) shortcut.activated.connect(self.buttonBox.button(button).click) return shortcut
def __init__(self, parent=None): QWidget.__init__(self, parent) self.secs = None self.recording = False self.flashMillisecs = 1000 self.flashTimes = [0, 250, 500, 750] self.resize(400, 400) self.mainLayout = QVBoxLayout() self.setLayout(self.mainLayout) self.talkInfoFont = QFont('Serif', 50, QFont.Light) self.countdownFont = QFont('Serif', 300, QFont.Light) self.talkInfoString = QLabel() self.mainLayout.addWidget(self.talkInfoString) self.talkInfoString.setFont(self.talkInfoFont) self.talkInfoString.setAlignment(Qt.AlignCenter) self.talkInfoString.setStyleSheet( "QLabel { background-color : white; color : black; }") self.countdownString = QLabel() self.mainLayout.addWidget(self.countdownString) self.countdownString.setFont(self.countdownFont) self.countdownString.setAlignment(Qt.AlignCenter) self.countdownString.setStyleSheet( "QLabel { background-color : white; color : black; }") self.countdownTimer = QTimer() self.countdownTimer.timeout.connect(self.timertick) self.flashTimer = QTimer() self.flashTimer.timeout.connect(self.flash_display_text) QShortcut(QKeySequence("Esc"), self, self.showNormal)
def __init__(self): super(_StatusBar, self).__init__() self.current_status = _STATUSBAR_STATE_SEARCH self._widgetStatus = QWidget() vbox = QVBoxLayout(self._widgetStatus) vbox.setContentsMargins(0, 0, 0, 0) vbox.setSpacing(0) #Search Layout self._searchWidget = SearchWidget() vbox.addWidget(self._searchWidget) #Replace Layout self._replaceWidget = ReplaceWidget() vbox.addWidget(self._replaceWidget) self._replaceWidget.setVisible(False) #Code Locator self._codeLocator = locator.CodeLocatorWidget() vbox.addWidget(self._codeLocator) self._codeLocator.setVisible(False) #File system completer self._fileSystemOpener = FileSystemOpener() vbox.addWidget(self._fileSystemOpener) self._fileSystemOpener.setVisible(False) self.addWidget(self._widgetStatus) # Not Configurable Shortcuts shortEscStatus = QShortcut(QKeySequence(Qt.Key_Escape), self) self.connect(shortEscStatus, SIGNAL("activated()"), self.hide_status) self.connect(self._searchWidget._btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._replaceWidget._btnCloseReplace, SIGNAL("clicked()"), lambda: self._replaceWidget.setVisible(False)) self.connect(self._fileSystemOpener.btnClose, SIGNAL("clicked()"), self.hide_status) self.connect(self._fileSystemOpener, SIGNAL("requestHide()"), self.hide_status) self.connect(self._codeLocator, SIGNAL("hidden()"), self.hide_status) #Register signals connections connections = ( { 'target': 'main_container', 'signal_name': 'currentEditorChanged(QString)', 'slot': self._handle_tab_changed }, { 'target': 'main_container', 'signal_name': 'updateLocator(QString)', 'slot': self._explore_file_code }, { 'target': 'projects_explorer', 'signal_name': 'updateLocator()', 'slot': self._explore_code }, ) IDE.register_signals('status_bar', connections) IDE.register_service('status_bar', self)
def initGui(self): for keyseq, slot in ( (Qt.CTRL + Qt.ALT + Qt.Key_K, self.__create_group), (Qt.CTRL + Qt.ALT + Qt.Key_S, self.__select_next_group), (Qt.CTRL + Qt.ALT + Qt.Key_N, self.__next_section), (Qt.CTRL + Qt.ALT + Qt.Key_B, self.__previous_section), ): short = QShortcut(QKeySequence(keyseq), self.__iface.mainWindow()) short.setContext(Qt.ApplicationShortcut) short.activated.connect(slot) self.__shortcuts.append(short) self.__menu = QMenu("Albion") self.__menu.aboutToShow.connect(self.__create_menu_entries) self.__iface.mainWindow().menuBar().addMenu(self.__menu) self.__toolbar = QToolBar("Albion") self.__iface.addToolBar(self.__toolbar) self.__toolbar.addAction(icon("log_strati.svg"), "stratigraphic log").triggered.connect( self.__log_strati_clicked) self.__toolbar.addWidget(self.__current_graph) self.__current_graph.currentIndexChanged[unicode].connect( self.__current_graph_changed) self.__toolbar.addWidget(self.__current_section) self.__current_section.currentIndexChanged[unicode].connect( self.__current_section_changed) self.__toolbar.addAction( icon("previous_line.svg"), "previous section (Ctrl+Alt+b)").triggered.connect( self.__previous_section) self.__toolbar.addAction( icon("next_line.svg"), "next section (Ctrl+Alt+n)").triggered.connect(self.__next_section) self.__toolbar.addAction(icon("line_from_selected.svg"), "create temporary section").triggered.connect( self.__section_from_selection) self.__viewer3d = QDockWidget("3D") self.__viewer3d.setWidget(Viewer3d()) self.__iface.addDockWidget(Qt.LeftDockWidgetArea, self.__viewer3d) self.__iface.mainWindow().tabifyDockWidget( self.__iface.mainWindow().findChild(QDockWidget, "Layers"), self.__viewer3d) self.__viewer3d_ctrl = QToolBar("3D controls") self.__viewer3d_ctrl.addWidget(ViewerControls( self.__viewer3d.widget())) self.__iface.addToolBar(self.__viewer3d_ctrl) QgsProject.instance().readProject.connect(self.__qgis__project__loaded) self.__qgis__project__loaded() # case of reload
def onSetupEditorButtons(self): """Add IO button to Editor""" if isinstance(self.parentWindow, AddCards): btn = self._addButton("new_occlusion", lambda o=self: onImgOccButton(self, "add"), _("Alt+a"), _("Add Image Occlusion (Alt+A/Alt+O)"), canDisable=False) elif isinstance(self.parentWindow, EditCurrent): btn = self._addButton( "edit_occlusion", lambda o=self: onImgOccButton(self, "editcurrent"), _("Alt+a"), _("Edit Image Occlusion (Alt+A/Alt+O)"), canDisable=False) else: btn = self._addButton("edit_occlusion", lambda o=self: onImgOccButton(self, "browser"), _("Alt+a"), _("Edit Image Occlusion (Alt+A/Alt+O)"), canDisable=False) # secondary hotkey: press_action = QAction(self.parentWindow, triggered=btn.animateClick) press_action.setShortcut(QKeySequence(_("Alt+o"))) btn.addAction(press_action)
def keySequence(self, event): # is key pressed or key released ? keyPressed = event.type() == QEvent.KeyPress # or-ed keys keys = 0 # check modifiers pressed if event.modifiers() & Qt.ControlModifier: keys = int(keys) | Qt.ControlModifier if event.modifiers() & Qt.AltModifier: keys = int(keys) | Qt.AltModifier if event.modifiers() & Qt.ShiftModifier: keys = int(keys) | Qt.ShiftModifier if event.modifiers() & Qt.MetaModifier: keys = int(keys) | Qt.MetaModifier if keyPressed: # get press key if event.key() in (Qt.Key_Control, Qt.Key_Alt, Qt.Key_AltGr, Qt.Key_Shift, Qt.Key_Meta, Qt.Key_Super_L, Qt.Key_Super_R, Qt.Key_Menu, Qt.Key_Hyper_L, Qt.Key_Hyper_R, Qt.Key_Help, Qt.Key_Direction_L, Qt.Key_Direction_R): pass else: # add pressed key keys = int(keys) | event.key() # set sequence finished self._finished = True # return human readable key sequence return QKeySequence(keys).toString()
def importShortcut(filename, widget, schemeWidget): """Loads shortcuts from a file""" try: d = ET.parse(filename) root = d.getroot() if root.tag != 'frescobaldi-shortcut': raise ValueError(_("No shortcuts found.")) except Exception as e: QMessageBox.critical(widget, app.caption(_("Error")), _("Can't read from source:\n\n{url}\n\n{error}").format( url=filename, error=e)) return schemeWidget.scheme.blockSignals(True) scheme = schemeWidget.addScheme(root.get('name')) schemeWidget.scheme.blockSignals(False) for col in root.findall('collection'): for name in col.findall('name'): shortcuts = [QKeySequence.fromString(shortcut.text) for shortcut in name.findall('shortcut')] item = widget.item(col.attrib['name'], name.attrib['name']) if item: item.setShortcuts(shortcuts, scheme) schemeWidget.disableDefault(False) schemeWidget.currentChanged.emit() schemeWidget.changed.emit()
def __init__(self, parent=None): super(PyboritaWidget, self).__init__(parent) self.parent = parent main_container = QVBoxLayout(self) ## Información puntaje box_score = QHBoxLayout() self._score = "<h2>Puntaje: %s</h2>" self.lbl_score = QLabel(self._score % 0) self.lbl_score.setStyleSheet("background: #232729") self.lbl_score.setAlignment(Qt.AlignCenter) box_score.addWidget(self.lbl_score) self._max_score = "<h2>Máximo Puntaje: %s</h2>" self.lbl_max_score = QLabel(self._max_score % 0) self.lbl_max_score.setStyleSheet("background: #232729") self.lbl_max_score.setAlignment(Qt.AlignCenter) box_score.addWidget(self.lbl_max_score) main_container.addLayout(box_score) # Snake self.frame_snake = pyborita.Pyborita() main_container.addWidget(self.frame_snake) main_container.setAlignment(Qt.AlignCenter) tecla_escape = QShortcut(QKeySequence(Qt.Key_Escape), self) # Conexiones tecla_escape.activated.connect(self._mostrar_dialogo) self.frame_snake.scoreChanged[int].connect(self.update_score) self.frame_snake.highscoreChanged[int].connect(self.update_max_score)
def __init__(self, mainwindow): super(MusicViewPanel, self).__init__(mainwindow) self.toggleViewAction().setShortcut(QKeySequence("Meta+Alt+M")) mainwindow.addDockWidget(Qt.RightDockWidgetArea, self) ac = self.actionCollection = Actions(self) actioncollectionmanager.manager(mainwindow).addActionCollection(ac) ac.music_print.triggered.connect(self.printMusic) ac.music_zoom_in.triggered.connect(self.zoomIn) ac.music_zoom_out.triggered.connect(self.zoomOut) ac.music_zoom_original.triggered.connect(self.zoomOriginal) ac.music_zoom_combo.zoomChanged.connect(self.slotZoomChanged) ac.music_fit_width.triggered.connect(self.fitWidth) ac.music_fit_height.triggered.connect(self.fitHeight) ac.music_fit_both.triggered.connect(self.fitBoth) ac.music_maximize.triggered.connect(self.maximize) ac.music_jump_to_cursor.triggered.connect(self.jumpToCursor) ac.music_sync_cursor.triggered.connect(self.toggleSyncCursor) ac.music_copy_image.triggered.connect(self.copyImage) ac.music_document_select.documentsChanged.connect(self.updateActions) ac.music_copy_image.setEnabled(False) ac.music_next_page.triggered.connect(self.slotNextPage) ac.music_prev_page.triggered.connect(self.slotPreviousPage) self.slotPageCountChanged(0) ac.music_next_page.setEnabled(False) ac.music_prev_page.setEnabled(False) ac.music_reload.triggered.connect(self.reloadView) self.actionCollection.music_sync_cursor.setChecked(QSettings().value( "musicview/sync_cursor", False, bool))
def test_functional(): app = QApplication(sys.argv) shortcut = QxtGlobalShortcut() shortcut.setShortcut(QKeySequence('Ctrl+Alt+E')) shortcut.activated.connect(app.exit) QTimer.singleShot(100, shortcut.activated.emit) app.exec_()
def __init__(self, mainwindow): QDialog.__init__(self, mainwindow, Qt.Tool) self._mainwindow = mainwindow self._ui = ui = Ui_Dialog() ui.setupUi(self) ui.actionFocusLineEdit = QAction(self) self.addAction(ui.actionFocusLineEdit) ui.actionFocusLineEdit.setShortcut(QKeySequence('Ctrl+L')) ui.actionFocusLineEdit.triggered.connect(self.setFocusOnPhraseBox) ui.treeWidget.itemChanged.connect(self.__onTreeItemChanged) ui.lineEditPhrase.textChanged.connect(self._update_buttons) ui.buttonReset.clicked.connect(self.__onReset) ui.buttonSearch.clicked.connect(self.__onSearch) ui.buttonReset.setDisabled(True) self._tree_checked = False ui.buttonSearch.setIcon(QIcon(':/icons/edit-find.png')) try: if 'advancedDialogGeometry' in get_config(): self.restoreGeometry(get_config()['advancedDialogGeometry']) except: pass self._update_buttons() self._load_tree()
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 = QDockWidget(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() self.connect(dock, SIGNAL('visibilityChanged(bool)'), self.visibility_changed) self.dockwidget = dock short = self.get_option("shortcut", None) if short is not None: shortcut = QShortcut(QKeySequence(short), self.main, self.switch_to_plugin) self.register_shortcut(shortcut, "_", "Switch to %s" % self.CONF_SECTION, default=short) return (dock, self.LOCATION)
def addLabelClass(self, label_config): # Check label configuration if 'attributes' not in label_config: raise ImproperlyConfigured("Label with no 'attributes' dict found") attrs = label_config['attributes'] if 'class' not in attrs: raise ImproperlyConfigured("Labels must have an attribute 'class'") label_class = attrs['class'] if label_class in self._class_config: raise ImproperlyConfigured("Label with class '%s' defined more than once" % label_class) # Store config self._class_config[label_class] = label_config # Parse configuration and create handlers and item self.parseConfiguration(label_class, label_config) # Add label class button button = QPushButton(label_class, self) button.setCheckable(True) button.setFlat(True) button.clicked.connect(bind(self.onClassButtonPressed, label_class)) self._class_buttons[label_class] = button self._classbox_layout.addWidget(button) # Add hotkey if 'hotkey' in label_config: hotkey = QShortcut(QKeySequence(label_config['hotkey']), self) hotkey.activated.connect(button.click) self._class_shortcuts[label_class] = hotkey
def register(self, default_keyseq, action_info): """ Register a new shortcut. :param default_keyseq: A string specifying the shortcut key, e.g. 's' or 'Ctrl+P' :param action_info: The details of the shortcut's target action. Must be of type ActionInfo (see above). """ default_keyseq = QKeySequence(default_keyseq) group, name, description, target_callable, context_widget, tooltip_widget = action_info assert context_widget is not None, "You must provide a context_widget" try: group_dict = self._action_infos[group] except KeyError: group_dict = self._action_infos[group] = collections.OrderedDict() try: action_set = group_dict[name] except KeyError: action_set = group_dict[name] = set() action_set.add(action_info) self.change_keyseq(group, name, None, default_keyseq) # If there was a preference for this keyseq, update our map to use it. try: stored_keyseq = self._preferences_reversemap[(group, name)] self.change_keyseq(group, name, default_keyseq, stored_keyseq) except KeyError: pass
def contextMenuEvent(self, event): def correctWord(cursor, word): # From QTextCursor doc: # if there is a selection, the selection is deleted and replaced return lambda: cursor.insertText(word) popup_menu = self.createStandardContextMenu() paste_action = popup_menu.actions()[6] paste_formatted_action = QAction(self.tr("Paste raw HTML"), popup_menu) paste_formatted_action.triggered.connect(self.insertFromRawHtml) paste_formatted_action.setShortcut(QKeySequence("Ctrl+Shift+V")) popup_menu.insertAction(paste_action, paste_formatted_action) # Spellcheck the word under mouse cursor, not self.textCursor cursor = self.cursorForPosition(event.pos()) cursor.select(QTextCursor.WordUnderCursor) text = cursor.selectedText() if self.speller and text: if not self.speller.check(text): lastAction = popup_menu.actions()[0] for word in self.speller.suggest(text)[:10]: action = QAction(word, popup_menu) action.triggered.connect(correctWord(cursor, word)) action.setFont(QFont(None, weight=QFont.Bold)) popup_menu.insertAction(lastAction, action) popup_menu.insertSeparator(lastAction) popup_menu.exec_(event.globalPos())
def remove_item(self, label_class): """ 删除标签 :param label_class: 删除的标签名字 """ try: # 删除快捷键 self.endInsertionMode() shortcut = self.label2shortcut[label_class] if shortcut in self.shortcut2button and \ self.shortcut2button[shortcut] is not None and \ self.shortcut2button[shortcut] == self._class_buttons[label_class]: self.shortcut2button[shortcut].setShortcut(QKeySequence()) del self.shortcut2button[shortcut] # 删除菜单 del self.label_menu[label_class] # 删除菜单的动作 del self.label_action[label_class] # 删除视图中的按钮 self._classbox_layout.removeWidget( self._class_buttons[label_class]) self._class_buttons[label_class].deleteLater() self._class_buttons[label_class] = None del self._class_config[label_class] # 写回json direct = os.path.dirname(sys.argv[0]) with open(os.path.join(direct, 'sloth.txt'), 'r') as f: label_path = f.read() try: with open(label_path, 'r') as f: temp = json5.load(f) for i, current_json in enumerate(temp): if current_json['attributes']['class'] == label_class: temp.remove(current_json) # 遍历combo box 找到要删的 for i in range(len(self.combo_box)): current_label = self.combo_box.itemText(i) if current_label == label_class: print('removed', label_class) self.combo_box.removeItem(i) self.items.pop(i) break self._class_buttons.pop(label_class) break with open(label_path, 'w') as f: json5.dump(temp, f, quote_keys=True, trailing_commas=False, indent=4, separators=(',', ': '), sort_keys=True, ensure_ascii=False) self._parea.setGeometry( 0, 0, 200, max(self._parea.geometry().height() - 40, 60)) except Exception as e: print(e) except Exception as e: print(e)
def __init__(self, parent): QDialog.__init__(self) self.form = Ui_Dialog() self.form.setupUi(self) self.form.tableView.horizontalHeader().setMovable(True) self.form.addButton.clicked.connect(self.onAdd) self.form.deleteButton.clicked.connect(self.onDelete) self.form.importButton.clicked.connect(self.onImport) self.form.exportButton.clicked.connect(self.onExport) self.form.closeButton.clicked.connect(self.reject) self.form.fastEditBox.toggled.connect(self.onChangeFastEdit) self.onChangeFastEdit() # set up initial state self.setupClassCombo() self.tableModel = StudentTableModel(self) self.form.tableView.setModel(self.tableModel) self.sm = self.form.tableView.selectionModel() self.sm.selectionChanged.connect(self.checkButtonEnablement) self.reFillStudents() self.form.classCombo.activated.connect(self.reFillStudents) self.tableModel.valueRejected.connect(self.onValueRejected) self.tableModel.rowsRemoved.connect(self._updateStudentTotal) self.tableModel.rowsInserted.connect(self._updateStudentTotal) self.tableModel.modelReset.connect(self._updateStudentTotal) self._updateStudentTotal() qlShortcut = QShortcut(QKeySequence("Alt+L"), self.form.tableView) qlShortcut.connect(qlShortcut, QtCore.SIGNAL("activated()"), lambda: self.form.tableView.setFocus())
def __init__(self): super(Demo, self).__init__() self.code_editor = CodeEditor(self) self.code_editor.setup_editor( language = "python", font = QFont("Courier New") ) run_sc = QShortcut(QKeySequence("F5"), self, self.run) self.shell = InternalShell(self, {"demo":self}, multithreaded = False, max_line_count = 3000, font = QFont("Courier new", 10), message='caonima' ) self.dict_editor = DictEditorWidget(self, {}) self.dict_editor.editor.set_filter(self.filter_namespace) self.dict_editor.set_data(self.shell.interpreter.namespace) vbox = QVBoxLayout() vbox.addWidget(self.code_editor) vbox.addWidget(self.shell) hbox = QHBoxLayout() hbox.addWidget(self.dict_editor) hbox.addLayout(vbox) self.setLayout(hbox) self.resize(800, 600)
def __init__(self, gui=True, **argv): """ gui: whether to show webkit window or run headless """ super(AjaxBrowser, self).__init__() self.argv = argv self.stats = stats.RenderStats() # use grid layout to hold widgets self.grid = QVBoxLayout() self.url_input = UrlInput(self.load_url) self.grid.addWidget(self.url_input) self._view = None # create status box self.status_table = StatusTable() self.grid.addWidget(self.status_table) # create results table self.records_table = ResultsTable() self.grid.addWidget(self.records_table) self.setLayout(self.grid) # log all responses response_filename = os.path.join(webkit.OUTPUT_DIR, 'responses.csv') self.response_writer = csv.writer(open(response_filename, 'w')) self.response_writer.writerow( ['URL', 'Content-Type', 'Referer', 'Size']) # Define keyboard shortcuts for convenient interaction QShortcut(QKeySequence.Close, self, self.close) QShortcut(QKeySequence.Quit, self, self.close) QShortcut(QKeySequence(Qt.CTRL + Qt.Key_F), self, self.fullscreen) if gui: self.showMaximized() self.raise_() # give focus to this browser window
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 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 )
def validateAction(self, row, column): if column != 1: return table = self.actionTable item = table.item(row, column) shortcutText = QKeySequence(item.text()).toString() thisRow = table.row(item) if not shortcutText.isEmpty(): for row in range(table.rowCount()): if row == thisRow: continue other = table.item(row, 1) if other.text() == shortcutText: other.setText(item.oldShortcutText) break item.setText(shortcutText) item.oldShortcutText = shortcutText table.resizeColumnToContents(1)
def shortcut(item): """Returns a suitable text for the keyboard shortcut of the given item. Item may be a QAction, a QShortcut, a QKeySequence or a QKeySequence.StandardKey. The text is meant to be used in the help docs. """ if isinstance(item, QAction): seq = item.shortcut() elif isinstance(item, QShortcut): seq = item.key() elif isinstance(item, QKeySequence.StandardKey): seq = QKeySequence(item) else: seq = item return seq.toString(QKeySequence.NativeText) or _("(no key defined)")
def eventFilter( self, object, event ): """ Filters out key press events for the shortcut section for this edit. :param object | <QObject> event | <QEvent> """ if ( object != self.uiShortcutTXT ): return False if ( event.type() == event.KeyPress ): seq = QKeySequence(event.key() + int(event.modifiers())) self.uiShortcutTXT.setText( seq.toString() ) return True elif ( event.type() == event.KeyRelease): return True return False
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 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 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])
def keybinding(attr): """Return keybinding""" ks = getattr(QKeySequence, attr) return QKeySequence.keyBindings(ks)[0].toString()
class ShortcutChooserWidget(QtGui.QWidget, FORM_CLASS): keyPressed = pyqtSignal() def __init__(self, parent=None): """ Initializates ShortcutChooserWidget """ super(ShortcutChooserWidget, self).__init__(parent) self.resetVariables() self.setupUi(self) @pyqtSlot(bool) def on_assignShortcutPushButton_clicked(self): """ After button is clicked, focus is needed to use keyPressEvent and keyReleaseEvent """ self.setFocus() @pyqtSlot(bool) def on_assignShortcutPushButton_toggled(self, toggled): """ Button toggled reset self.modifiers and self.keys and also prepairs button text """ if toggled: self.resetVariables() self.assignShortcutPushButton.setText(self.tr('Enter Value')) @pyqtSlot(bool, name = 'on_clearPushButton_clicked') def clearAll(self): """ Clears push button and also resets self.modifiers and self.keys """ self.assignShortcutPushButton.setChecked(False) self.assignShortcutPushButton.setText(self.tr('Assign Shortcut')) self.resetVariables() def resetVariables(self): """ Resets self.modifiers, self.key and self.keySequence to 0 """ self.modifiers = 0 self.key = 0 self.keySequence = 0 def keyPressEvent(self, event): """ """ if not self.assignShortcutPushButton.isChecked(): super(ShortcutChooserWidget, self).keyPressEvent(event) return key = int(event.key()) if key == Qt.Key_Meta: self.modifiers |= Qt.META self.updateShortcutText() elif key == Qt.Key_Alt: self.modifiers |= Qt.ALT self.updateShortcutText() elif key == Qt.Key_Control: self.modifiers |= Qt.CTRL self.updateShortcutText() elif key == Qt.Key_Shift: self.modifiers |= Qt.SHIFT self.updateShortcutText() elif key == Qt.Key_Escape: self.assignShortcutPushButton.setChecked(False) return else: self.key = key self.updateShortcutText() def keyReleaseEvent(self, event): if not self.assignShortcutPushButton.isChecked(): super(ShortcutChooserWidget, self).keyReleaseEvent(event) return key = event.key() if key == Qt.Key_Meta: self.modifiers &= Qt.META self.updateShortcutText() elif key == Qt.Key_Alt: self.modifiers &= Qt.ALT self.updateShortcutText() elif key == Qt.Key_Control: self.modifiers &= Qt.CTRL self.updateShortcutText() elif key == Qt.Key_Shift: self.modifiers &= Qt.SHIFT self.updateShortcutText() elif key == Qt.Key_Escape: return else: self.assignShortcutPushButton.setChecked(False) self.updateShortcutText() self.setShortcut(self.keySequence) def setEnabled(self, enabled): if not enabled: self.clearAll() super(ShortcutChooserWidget, self).setEnabled(enabled) def setShortcut(self, shortcut): self.keySequence = QKeySequence(shortcut) self.assignShortcutPushButton.setChecked(False) self.assignShortcutPushButton.setText(self.keySequence.toString(format = QKeySequence.NativeText)) def getShortcut(self, asQKeySequence = False): if asQKeySequence: return self.keySequence else: return int(self.keySequence) def updateShortcutText(self): self.keySequence = QKeySequence(self.modifiers+self.key) #this uses QKeySequence.NativeText to show in the interface. To store data, no filter should be provided self.assignShortcutPushButton.setText(self.tr('Input: {0}').format(self.keySequence.toString(format = QKeySequence.NativeText)))
def shortcut(self): return QKeySequence.fromString(self.text())
def build_ui(self, options, configuration): """ This is all the twisted logic of setting up the UI, which is re-run whenever the browser is "reset" by the user. """ debug("build_ui") inactivity_timeout = options.timeout or int(configuration.get("timeout", 0)) timeout_mode = configuration.get('timeout_mode', 'reset') self.refresh_timer = int(configuration.get("refresh_timer", 0)) self.icon_theme = options.icon_theme or configuration.get("icon_theme", None) self.zoomfactor = options.zoomfactor or float(configuration.get("zoom_factor") or 1.0) self.allow_popups = options.allow_popups or configuration.get("allow_popups", False) self.ssl_mode = (configuration.get("ssl_mode") in ['strict', 'ignore'] and configuration.get("ssl_mode")) or 'strict' self.is_fullscreen = options.is_fullscreen or configuration.get("fullscreen", False) self.show_navigation = not options.no_navigation and configuration.get('navigation', True) self.navigation_layout = configuration.get( "navigation_layout", ['back', 'forward', 'refresh', 'stop', 'zoom_in', 'zoom_out', 'separator', 'bookmarks', 'separator', 'spacer', 'quit']) self.content_handlers = self.configuration.get("content_handlers", {}) self.allow_external_content = options.allow_external_content or self.configuration.get("allow_external_content", False) self.allow_plugins = options.allow_plugins or self.configuration.get("allow_plugins", False) self.privacy_mode = self.configuration.get("privacy_mode", True) self.quit_button_mode = self.configuration.get("quit_button_mode", 'reset') self.quit_button_text = self.configuration.get("quit_button_text", "I'm &Finished") self.quit_button_tooltip = (self.quit_button_mode == 'close' and "Click here to quit the browser.") or \ """Click here when you are done.\nIt will clear your browsing history and return you to the start page.""" self.window_size = options.window_size or self.configuration.get("window_size", None) self.allow_printing = self.configuration.get("allow_printing", False) qb_mode_callbacks = {'close': self.close, 'reset': self.reset_browser} to_mode_callbacks = {'close': self.close, 'reset': self.reset_browser, 'screensaver': self.screensaver} #If the whitelist is activated, add the bookmarks and start_url if self.whitelist: # we can just specify whitelist = True, #which should whitelist just the start_url and bookmark urls. if type(self.whitelist) is not list: self.whitelist = [] self.whitelist.append(str(QUrl(self.start_url).host())) bookmarks = self.configuration.get("bookmarks") if bookmarks: self.whitelist += [str(QUrl(b.get("url")).host()) for k,b in bookmarks.items()] self.whitelist = list(set(self.whitelist)) #uniquify self.whitelist = [item.replace(".", "\.") for item in self.whitelist] #escape dots debug("Generated whitelist: " + str(self.whitelist)) ###Start GUI configuration### self.browser_window = WcgWebView( allow_popups=self.allow_popups, default_user=self.default_user, default_password=self.default_password, zoomfactor=self.zoomfactor, content_handlers=self.content_handlers, allow_external_content=self.allow_external_content, html404=self.html404, html_network_down=self.html_network_down, start_url=self.start_url, ssl_mode=self.ssl_mode, allow_plugins = self.allow_plugins, whitelist = self.whitelist, allow_printing = self.allow_printing, proxy_server = self.proxy_server, privacy_mode = self.privacy_mode ) self.browser_window.setObjectName("web_content") if self.icon_theme is not None and QT_VERSION_STR > '4.6': QIcon.setThemeName(self.icon_theme) self.setCentralWidget(self.browser_window) debug(options) debug("loading %s" % self.start_url) self.browser_window.setUrl(QUrl(self.start_url)) if self.is_fullscreen is True: self.showFullScreen() elif self.window_size and self.window_size.lower() == 'max': self.showMaximized() elif self.window_size: size = re.match(r"(\d+)x(\d+)", self.window_size) if size: width, height = size.groups() self.setFixedSize(int(width), int(height)) else: debug("Ignoring invalid window size \"%s\"" % self.window_size) #Set up the top navigation bar if it's configured to exist if self.show_navigation is True: self.navigation_bar = QToolBar("Navigation") self.navigation_bar.setObjectName("navigation") self.addToolBar(Qt.TopToolBarArea, self.navigation_bar) self.navigation_bar.setMovable(False) self.navigation_bar.setFloatable(False) #Standard navigation tools self.nav_items = {} self.nav_items["back"] = self.browser_window.pageAction(QWebPage.Back) self.nav_items["forward"] = self.browser_window.pageAction(QWebPage.Forward) self.nav_items["refresh"] = self.browser_window.pageAction(QWebPage.Reload) self.nav_items["stop"] = self.browser_window.pageAction(QWebPage.Stop) #The "I'm finished" button. self.nav_items["quit"] = self.createAction( self.quit_button_text, qb_mode_callbacks.get(self.quit_button_mode, self.reset_browser), QKeySequence("Alt+F"), None, self.quit_button_tooltip) #Zoom buttons self.nav_items["zoom_in"] = self.createAction( "Zoom In", self.zoom_in, QKeySequence("Alt++"), "zoom-in", "Increase the size of the text and images on the page") self.nav_items["zoom_out"] = self.createAction( "Zoom Out", self.zoom_out, QKeySequence("Alt+-"), "zoom-out", "Decrease the size of text and images on the page") if self.allow_printing: self.nav_items["print"] = self.createAction("Print", self.browser_window.print_webpage, QKeySequence("Ctrl+p"), "document-print", "Print this page") #Add all the actions to the navigation bar. for item in self.navigation_layout: if item == "separator": self.navigation_bar.addSeparator() elif item == "spacer": #an expanding spacer. spacer = QWidget() spacer.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) self.navigation_bar.addWidget(spacer) elif item == "bookmarks": #Insert bookmarks buttons here. self.bookmark_buttons = [] if configuration.get("bookmarks"): for bookmark in configuration.get("bookmarks").items(): debug("Bookmark:\n" + bookmark.__str__()) #bookmark name will use the "name" attribute, if present #or else just the key: bookmark_name = bookmark[1].get("name") or bookmark[0] #Create a button for the bookmark as a QAction, #which we'll add to the toolbar button = self.createAction( bookmark_name, lambda url=bookmark[1].get("url"): self.browser_window.load(QUrl(url)), QKeySequence.mnemonic(bookmark_name), None, bookmark[1].get("description") ) self.navigation_bar.addAction(button) self.navigation_bar.widgetForAction(button).setObjectName("navigation_button") else: action = self.nav_items.get(item, None) if action: self.navigation_bar.addAction(action) self.navigation_bar.widgetForAction(action).setObjectName("navigation_button") #This removes the ability to toggle off the navigation bar: self.nav_toggle = self.navigation_bar.toggleViewAction() self.nav_toggle.setVisible(False) #End "if show_navigation is True" block # set hidden quit action # For reasons I haven't adequately ascertained, #this shortcut fails now and then claiming "Ambiguous shortcut overload". # No idea why, as it isn't consistent. self.really_quit = self.createAction("", self.close, QKeySequence("Ctrl+Alt+Q"), None, "") self.addAction(self.really_quit) #Call a reset function after timeout if inactivity_timeout != 0: self.event_filter = InactivityFilter(inactivity_timeout) QCoreApplication.instance().installEventFilter(self.event_filter) self.browser_window.page().installEventFilter(self.event_filter) self.connect(self.event_filter, SIGNAL("timeout()"), to_mode_callbacks.get(timeout_mode, self.reset_browser)) else: self.event_filter = None if self.refresh_timer != 0: # Create a QTimer self.timer = QTimer() # Connect it to self.refresh_browser self.timer.timeout.connect(self.refresh_browser) # Call refresh_browser() every self.refresh_timer seconds self.timer.start(self.refresh_timer*1000)
def setShortcut(self, shortcut): self.keySequence = QKeySequence(shortcut) self.assignShortcutPushButton.setChecked(False) self.assignShortcutPushButton.setText(self.keySequence.toString(format = QKeySequence.NativeText))
def updateShortcutText(self): self.keySequence = QKeySequence(self.modifiers+self.key) #this uses QKeySequence.NativeText to show in the interface. To store data, no filter should be provided self.assignShortcutPushButton.setText(self.tr('Input: {0}').format(self.keySequence.toString(format = QKeySequence.NativeText)))
def stringWithAppendedShortcut(string: str, shortcut: QKeySequence) -> str: """ :returns: An HTML string that contains the given string with a suffixed shortcut key in grey. """ s = shortcut.toString(QKeySequence.NativeText) return "{0} <span style=\"color: gray; font-size: small\">{1}</span>".format(string, s)
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()