def copy_selection(self): # get selection index selection = self.TableView.selectedIndexes() if selection: # create table data container rows = sorted(index.row() for index in selection) cols = sorted(index.column() for index in selection) row_count = rows[-1] - rows[0] + 1 col_count = cols[-1] - cols[0] + 1 table = [[''] * col_count for _ in range(row_count)] # table data container # fill data into the container for index in selection: row = index.row() - rows[0] column = index.column() - cols[0] table[row][column] = index.data() # data to clipboard stream = io.StringIO() csv.writer(stream, delimiter='\t').writerows(table) QtGui.QClipboard().setText(stream.getvalue()) return
def copy_to_clipboard(self, nodes=None): nodes = nodes or self.selected_nodes() if not nodes: return pipes = self.get_pipes_from_nodes(nodes) serializer = SessionSerializer(nodes, pipes) clipboard = QtGui.QClipboard() clipboard.setText(serializer.serialize_to_str())
def open_url(self, url): """We're handling the clicking of anchors here manually.""" if not url.isValid(): return file_info = QtCore.QFileInfo(url.url()) if file_info.exists(): common.reveal(file_info.filePath()) QtGui.QClipboard().setText(file_info.filePath()) else: QtGui.QDesktopServices.openUrl(url)
def copy_path(path, mode=WindowsPath, first=True, copy=True): """Copy a file path to the clipboard. The path will be conformed to the given `mode` (eg. forward slashes converted to back-slashes for `WindowsPath`). Args: path (unicode): Description of parameter `path`. mode (int): Any of `WindowsPath`, `UnixPath`, `SlackPath` or `MacOSPath`. Defaults to `WindowsPath`. first (bool): If `True` copy the first item of a sequence. copy (bool): If copy is false the converted path won't be copied to the clipboard. Defaults to `True`. Returns: unicode: The converted path. """ if first: path = get_sequence_startpath(path) else: path = get_sequence_endpath(path) # Normalise path path = re.sub(ur'[\/\\]', ur'/', path, flags=re.IGNORECASE | re.UNICODE).strip(u'/') if mode == WindowsPath: prefix = u'//' if u':' not in path else u'' elif mode == UnixPath: prefix = u'//' if u':' not in path else u'' elif mode == SlackPath: prefix = u'file://' elif mode == MacOSPath: prefix = u'smb://' path = path.replace(u':', u'') else: prefix = u'' path = prefix + path if mode == WindowsPath: path = re.sub(ur'[\/\\]', ur'\\', path, flags=re.IGNORECASE | re.UNICODE) if copy: QtGui.QClipboard().setText(path) import bookmarks.log as log log.success(u'Copied {}'.format(path)) return path
def keyPressEvent(self, event): if event.matches(QtGui.QKeySequence.Paste): try: clip = QtGui.QClipboard() img = clip.image() if img.isNull(): return super(ScrollWidget, self).keyPressEvent(event) temp = tempfile.gettempdir() + os.sep + uuid.uuid4().hex + ".png" img.save(temp) self.top_w.add_image_from_clip(temp) except Exception as e: print("Invalid clipboard: " + str(e)) super(ScrollWidget, self).keyPressEvent(event)
def __init__(self, parent=None): QtWidgets.QMainWindow.__init__(self) self.setupUi(self) self.setWindowTitle(__appname__ + " (v. " + __version__ + ")") self.configfile = os.path.join(appDataPath, "settings.ini") self.settings = QtCore.QSettings(self.configfile, QtCore.QSettings.IniFormat) self.settings.setIniCodec("UTF-8") self.clip = QtGui.QClipboard() self.adTree.itemClicked.connect(self.adTreeItemClicked) self.buttonPasteFIO.clicked.connect(self.buttonPasteFIOClicked) self.buttonPasteF.clicked.connect(self.buttonPasteFClicked) self.buttonPasteI.clicked.connect(self.buttonPasteIClicked) self.buttonPasteO.clicked.connect(self.buttonPasteOClicked) self.loginTemplate.textEdited.connect(self.loginTemplateEmitted) self.passwordMask.textEdited.connect(self.passwordMaskEmitted) self.buttonGenLogins.clicked.connect(self.buttonGenLoginsClicked) self.buttonCopyLogins.clicked.connect(self.copySelectedToClipboard) self.lineEditAttribute.textEdited.connect( self.lineEditAttributeEmitted) self.comboBoxAttributes.activated.connect( self.comboBoxAttributesActivated) self.checkboxAddToGroup.stateChanged.connect( self.checkboxAddToGroupStateChanged) self.comboboxGroups.activated.connect(self.comboboxGroupsActivated) self.buttonConnectToAD.clicked.connect(self.buttonConnectToADClicked) self.buttonTestAccounts.clicked.connect(self.testADAccounts) self.buttonCreateAccounts.clicked.connect(self.createADAccounts) self.buttonConnectToAD.hide() self.adServer.hide() self.adUser.hide() self.adPassword.hide() self.initSettings() self.loadAdToUI()
def button_menu(self, name, func, *args): """ Menu for the buttons in the tab Args: name (str): The name of the function (for excluding) func (callable): The function instance (for looking up the docstring) """ menu = QtWidgets.QMenu() menu.addAction( 'Copy Script Path to Clipboard', lambda: QtGui.QClipboard().setText(self.data.get('script'))) menu.addAction( 'Open Script in Default Editor', lambda: os.system('start {}'.format(self.data.get('script')))) menu.addSeparator() menu.addAction('Exclude Button', lambda: self.add_exclude(name)) menu.addAction('Print Source Function Docstring', lambda: sys.stdout.write('{}\n'.format(func.__doc__))) menu.exec_(QtGui.QCursor.pos())
def tab_menu(self, *args): """ Menu for the overall tab widget. """ if 'script' not in self.data: return menu = QtWidgets.QMenu() menu.addAction('Refresh Tab', self.process_script) menu.addAction( 'Copy Script Path to Clipboard', lambda: QtGui.QClipboard().setText(self.data.get('script'))) menu.addAction( 'Open Script in Default Editor', lambda: os.system('start {}'.format(self.data.get('script')))) if self.data.get('excluded'): menu.addSeparator() hidden_menu = menu.addMenu('Include Excluded Button(s)') for button in self.data.get('excluded', []): hidden_menu.addAction(button, partial(self.remove_exclude, button)) menu.addAction('Include All Excluded Buttons', self.remove_exclude) menu.exec_(QtGui.QCursor.pos())
def paste_from_clipboard(self): clipboard = QtGui.QClipboard() data_string = clipboard.text() self._undo_stack.beginMacro('pasted nodes') self.load_nodes_data(data_string) self._undo_stack.endMacro()
def copyMarkdownLink(): nm = currentNote._name rd = currentNote._details["randomString"] txt = "[" + nm + "](./" + rd + ")" QtGui.QClipboard().setText(txt)
def eventFilter(self, obj, event): """ Args: obj (QTextEdit) Filter and handle key events (only). """ if event.type() == event.KeyPress: # handle "embracing" character if some text is selected key = event.key() if event.modifiers() == (QtCore.Qt.AltModifier | QtCore.Qt.ControlModifier): # add new multi-cursor under current one if key == QtCore.Qt.Key_Down: multi_handler = self.get_multi_handler() multi_handler.add_cursor_from_key('down') return True # add new multi-cursor above current one if key == QtCore.Qt.Key_Up: multi_handler = self.get_multi_handler() multi_handler.add_cursor_from_key('up') return True cursor = self.get_cursor(obj) if event.modifiers() == (QtCore.Qt.ShiftModifier | QtCore.Qt.ControlModifier): # handle lines duplication on Ctrl+Shift+D if key == QtCore.Qt.Key_D: cursor.duplicate_lines() return True # extend selections on previous/next word on Ctrl +Shift +Left/Right if key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right): cursor.extend_selections(key, by_word=True) return True return False if event.modifiers() == (QtCore.Qt.ControlModifier | QtCore.Qt.KeypadModifier): # handle block comments on Ctrl+Shift+/ if event.key() == QtCore.Qt.Key_Slash: cursor.toggle_block_comment(self.comment_char) return True return False if event.modifiers() == QtCore.Qt.ControlModifier: # move lines on Ctrl +down/up if key == QtCore.Qt.Key_Down: return cursor.move_lines('down') if key == QtCore.Qt.Key_Up: return cursor.move_lines('up') if key in (QtCore.Qt.Key_Left, QtCore.Qt.Key_Right): operation = cursor.get_move_operation_from_key( key, by_word=True) cursor.multi_movePosition(operation, cursor.MoveAnchor) return True # paste on Ctrl +V if key == QtCore.Qt.Key_V: text = QtGui.QClipboard().text() cursor.insertText(text) return True # clear multi-cursors on Ctrl +A and select all if key == QtCore.Qt.Key_A: multi_manager = self.get_multi_handler() multi_manager.clear_cursors() cursor = multi_manager.cursors[-1] cursor.movePosition(cursor.Start, cursor.MoveAnchor) cursor.movePosition(cursor.End, cursor.KeepAnchor) self.parent().setTextCursor(cursor) return True return False if event.modifiers() == QtCore.Qt.ShiftModifier: # extend selections on Shift +cursor move if key in kk.MOVE_KEYS: cursor.extend_selections(key) return True if key in kk.MOVE_KEYS: operation = cursor.get_move_operation_from_key(key) cursor.multi_movePosition(operation, cursor.MoveAnchor) return True # handle embracing characters if event.text() == '`': return cursor.embrace_text_with('`', '`') if key == QtCore.Qt.Key_ParenLeft: return cursor.embrace_text_with('(', ')') if key == QtCore.Qt.Key_BracketLeft: return cursor.embrace_text_with('[', ']') if key == QtCore.Qt.Key_BraceLeft: return cursor.embrace_text_with('{', '}') if key == QtCore.Qt.Key_ParenRight: return cursor.ignore_if_next(')') if key == QtCore.Qt.Key_BracketRight: return cursor.ignore_if_next(']') if key == QtCore.Qt.Key_BraceRight: return cursor.ignore_if_next('}') if key == QtCore.Qt.Key_QuoteDbl: return cursor.embrace_text_with('"', '"') if key == QtCore.Qt.Key_Apostrophe: return cursor.embrace_text_with('\'', '\'') # handle blocks unindent if key == QtCore.Qt.Key_Backtab: cursor.unindent() return True # delete if event.key() == QtCore.Qt.Key_Delete: cursor.deleteChar() block = cursor.block() return True # backspace if event.key() == QtCore.Qt.Key_Backspace: return cursor.handle_backspace() # any other cases text = event.text() if text and text in kk.CHARACTERS: cursor.insertText(text) return True if text and text in kk.SPECIAL_CHARS: cursor.insertText(text) return True # handle event as usual if nothing has been filtered ahead return False
def getClipboardText(): import PySide2.QtGui as qtg return qtg.QClipboard().text()
def setClipboardText(text): import PySide2.QtGui as qtg qtg.QClipboard().setText(text)