def copy_clipboard(self): from io import BytesIO buf = BytesIO() self.fig.savefig(buf) QApplication.clipboard().setImage(QImage.fromData(buf.getvalue())) buf.close()
def copy_to_clipboard(plot): # pass # @staticmethod # def wx_copy_to_clipboard(plot): # # WX specific, though QT implementation is similar using # # QImage and QClipboard # import wx # width, height = plot.outer_bounds # gc = PlotGraphicsContext((width, height), dpi=72) backbuffer = plot.use_backbuffer plot.use_backbuffer = False gc.render_component(plot) plot.use_backbuffer = backbuffer # # # Create a bitmap the same size as the plot # # and copy the plot data to it bmp = gc.bmp_array if gc.format().startswith('bgra'): bmp_rgba = bmp[:, :, [2, 1, 0, 3]] else: bmp_rgba = bmp bitmap = QImage(bmp_rgba.tostring(), width, height, PySide.QtGui.QImage.Format_RGB32) if QApplication.clipboard(): QApplication.clipboard().setImage(bitmap.copy()) else: PySide.QtGui.QMessageBox("Unable to open the clipboard.", "Error")
def copy_to_clipboard(plot): # pass # @staticmethod # def wx_copy_to_clipboard(plot): # # WX specific, though QT implementation is similar using # # QImage and QClipboard # import wx # width, height = plot.outer_bounds # gc = PlotGraphicsContext((width, height), dpi=72) backbuffer = plot.use_backbuffer plot.use_backbuffer = False gc.render_component(plot) plot.use_backbuffer = backbuffer # # # Create a bitmap the same size as the plot # # and copy the plot data to it bmp = gc.bmp_array if gc.format().startswith('bgra'): bmp_rgba = bmp[:,:,[2,1,0,3]] else: bmp_rgba = bmp bitmap=QImage(bmp_rgba.tostring(),width,height, PySide.QtGui.QImage.Format_RGB32) if QApplication.clipboard(): QApplication.clipboard().setImage(bitmap.copy()) else: PySide.QtGui.QMessageBox("Unable to open the clipboard.", "Error")
def set_clipboard_image(self): """Export the formatted output to an image and store it in the clipboard. The image stored in the clipboard is a PNG file with alpha transparency. """ div = self.view.page().mainFrame().findFirstElement('.output') images = {} for background in (Qt.transparent, Qt.white): image = QImage(div.geometry().size(), QImage.Format_ARGB32_Premultiplied) image.fill(background) painter = QPainter(image) div.render(painter) painter.end() images[background] = image # Windows needs this buffer hack to get alpha transparency in # the copied PNG. buffer_ = QBuffer() buffer_.open(QIODevice.WriteOnly) images[Qt.transparent].save(buffer_, 'PNG') buffer_.close() data = QMimeData() data.setData('PNG', buffer_.data()) data.setImageData(images[Qt.white]) QApplication.clipboard().setMimeData(data)
def copy(self): """Copy to the clipboard""" data = QMimeData() text = '\n'.join([cursor.selectedText() \ for cursor in self.cursors()]) data.setText(text) data.setData(self.MIME_TYPE, text.encode('utf8')) QApplication.clipboard().setMimeData(data)
def clipboard_handler(event): if event.key == 'ctrl+c': # store the image in a buffer using savefig(), this has the # advantage of applying all the default savefig parameters # such as background color; those would be ignored if you simply # grab the canvas using Qt buf = io.BytesIO() fig.savefig(buf) QApplication.clipboard().setImage(QImage.fromData(buf.getvalue())) buf.close()
def toolsetLoader(fullFileName): if FILE_FILTER != None: data = fileFilter(fullFileName, FILE_FILTER) #TODO: find better way to paste filtred script QApplication.clipboard().setText(data) nuke.nodePaste("%clipboard%") # paste into nuke DAG else: nuke.loadToolset(fullFileName) return True
def copy_slot(self): # Collect the rows indices indices = self.table_view.selectedIndexes() if not indices: return min_row = max_row = indices[0].row() min_col = max_col = indices[0].column() def min_max(minimum, v, maximum): if v < minimum: return v, maximum elif v > maximum: return minimum, v else: return minimum, maximum for ndx in self.table_view.selectedIndexes(): min_row, max_row = min_max(min_row, ndx.row(), max_row) min_col, max_col = min_max(min_col, ndx.column(), max_col) mainlog.debug("Copy from {},{} to {},{}".format( min_row, min_col, max_row, max_col)) day_max = calendar.monthrange(self.base_date.year, self.base_date.month)[1] s = "" for r in range(min_row, max_row + 1): d = [] for c in range(min_col, max_col + 1): ndx = self._table_model.item(r, c) if c == 0 or c > day_max: d.append(ndx.data(Qt.DisplayRole) or "") else: t = ndx.data(Qt.UserRole + 1) # Day off if t: t = ndx.data(Qt.DisplayRole) else: hours = ndx.data(Qt.UserRole) # Activity hours if hours is not None: t = str(hours).replace('.', ',') else: t = "" d.append(t) s += "\t".join(d) + u"\n" QApplication.clipboard().setText(s)
def set_clipboard_word(self): """Store the formatted output in the clipboard in a Microsoft Word friendly format. Microsoft Word interprets the clipboard contents as an equation. Other programs will see it as plain text containing XML. """ QApplication.clipboard().setText(generic.word_equation_from_mathml( self.view.page().mainFrame().evaluateJavaScript(generic.MML_JS)))
def copy(self, *args): text = '' for row in self.dump(): text += '\t'.join([str(item) for item in row]) + os.linesep clipboard = QApplication.clipboard() clipboard.setText(text)
def __init__(self, parent=None): super(Widget, self).__init__(parent) # Initialize base gui widgets and objects self.text, self.info = Text(self), Info() self.clip = QApplication.clipboard() # Initialize composition self.compose({ QHBoxLayout(): [self.text, self.info] }) # Initialize events self.clip.dataChanged.connect(self.clipped) # Initialize styles and position self.widgetize('Tuci') #self.setAttribute(Qt.WA_TranslucentBackground) # remove this #self.setAttribute(Qt.WA_NoSystemBackground) # remove this too self.setAutoFillBackground(True) # Either this, or use transparent png as a mask # TODO: move into widgetize() self.setWindowOpacity(0.85) # Move to separate qss stylesheet # SEE: http://homyakovda.blogspot.ru/2011/04/blog-post.html self.setStyleSheet(''' QWidget { background-color: #a0b0d0; border: 2px solid white; } ''') #self.position() self.scale()
def _paste(self): clipboard = QApplication.clipboard() md = clipboard.mimeData() items = md.instance() if items is not None: editor = self._editor model = editor.model insert_mode = 'after' selection = self.selectedIndexes() if len(selection): offset = 1 if insert_mode == 'after' else 0 idx = selection[-1].row() + offset else: idx = len(editor.value) if self._cut_indices: if not any((ci <= idx for ci in self._cut_indices)): idx += len(self._cut_indices) model = editor.model for ci in self._cut_indices: model.removeRow(ci) self._cut_indices = None # paste_func = self.paste_func # if paste_func is None: # paste_func = lambda x: x.clone_traits() for ri, ci in reversed(items): model.insertRow(idx, obj=ci)
def _paste(self): clipboard = QApplication.clipboard() md = clipboard.mimeData() items = md.instance() if items is not None: editor = self._editor model = editor.model insert_mode = 'after' selection = self.selectedIndexes() if len(selection): offset = 1 if insert_mode == 'after' else 0 idx = selection[-1].row() + offset else: idx = len(editor.value) if self._cut_indices: if not any((ci <= idx for ci in self._cut_indices)): idx += len(self._cut_indices) model = editor.model for ci in self._cut_indices: model.removeRow(ci) self._cut_indices = None paste_func = self.paste_func if paste_func is None: paste_func = lambda x: x.clone_traits() for ri, ci in reversed(items): model.insertRow(idx, obj=paste_func(ci))
def getPythonSelection(self): """Get the Python selection and stuff it in: hiero.selectedItems""" self.updateActiveViewSelection() print "Selection copied to 'hiero.selectedItems':\n", self._selection clipboard = QApplication.clipboard() clipboard.setText("hiero.selectedItems") hiero.selectedItems = self._selection
def accept(self): clipboard = QApplication.clipboard() text = self.copyTextLineEdit.text() or self.panel.currentChar clipboard.setText(text, QClipboard.Clipboard) clipboard.setText(text, QClipboard.Selection) if text: say("Copied โ{}โ to the clipboard".format(text), SAY_TIMEOUT) super().accept()
def copy_cs(self): if len(self.gui.tableView.selectionModel().selectedIndexes()) == 0: return clipboard = QApplication.clipboard() selected_index = self.gui.tableView.selectionModel().selectedIndexes()[0] selected_text = str(self.tbm.data(selected_index)) clipboard.setText(selected_text)
def copy(self): if len(self.view.tableView.selectionModel().selectedIndexes()) == 0: return clipboard = QApplication.clipboard() selected_index = self.view.tableView.selectionModel().selectedIndexes()[0] selected_text = str(self.table_model.data(selected_index)) clipboard.setText(selected_text)
def paste_string(node_string): """ Pastes a given string and restore the previous clipboard""" clip = QApp.clipboard() bkp_txt = clip.text() clip.setText(node_string) nuke.nodePaste(r'%clipboard%') # restore previous clipboard clip.setText(bkp_txt)
def getPythonSelection(self): """Get the Clip media path in the active View and stuff it in: hiero.selectedClipPaths""" selection = self.getClipPathsForActiveView() if selection: hiero.selectedClipPaths = selection clipboard = QApplication.clipboard() clipboard.setText(str(hiero.selectedClipPaths)) print "Clip media path selection copied to Clipboard and stored in: hiero.selectedClipPaths:\n", selection
def copy_to_clipboard(plot): width, height = plot.outer_bounds gc = PlotGraphicsContext((width, height), dpi=72) backbuffer = plot.use_backbuffer plot.use_backbuffer = False gc.render_component(plot) plot.use_backbuffer = backbuffer # Create a bitmap the same size as the plot # and copy the plot data to it bmp = gc.bmp_array cache_bmp = bmp.tobytes() bitmap = QImage(cache_bmp, width+1, height+1, QImage.Format_RGB32) if QApplication.clipboard(): QApplication.clipboard().setImage(bitmap.copy(), QClipboard.Clipboard) else: PySide.QtGui.QMessageBox("Unable to open the clipboard.", "Error")
def action_copy_cell(self): if self.cell_selected(): clipboard = QApplication.clipboard() index = self.first_selected_index() text = self.table_model.data(index) clipboard.setText(str(text)) return True else: # TODO return False
def testQClipboard(self): #skip this test on MacOS because the clipboard is not available during the ssh session #this cause problems in the buildbot if sys.platform == 'darwin': return clip = QApplication.clipboard() clip.setText("Testing this thing!") text, subtype = clip.text("") self.assertEqual(subtype, "plain") self.assertEqual(text, "Testing this thing!")
def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.stopSign = 0 self.ws = 0 self.comment = '' self.clipboard = QApplication.clipboard() self.setWindowTitle(u'ๅคๅ่กจ') self.setWindowIcon(QIcon('./img/tray.png')) self.systemTrayIcon = QSystemTrayIcon(self) self.systemTrayIcon.setIcon(QIcon('./img/tray.png')) self.systemTrayIcon.setVisible(True) self.systemTrayIcon.show() self.systemTrayIcon.activated.connect(self.on_systemTrayIcon_activated) self.tableLabel = QLabel('select *.xls file') self.pathText = QLineEdit() self.triggerBtn = QPushButton(u'ๆชขๆฅ / ้ๅง') self.browseBtn = QPushButton(u' ็่ฆฝ ') self.stopBtn = QPushButton(u'ๅๆญข') self.table = QTableWidget(26,0,self) self.setUpTable() self.hbox1 = QHBoxLayout() self.hbox2 = QHBoxLayout() self.hbox3 = QHBoxLayout() self.hbox4 = QHBoxLayout() self.hbox1.addWidget(self.pathText) self.hbox1.addWidget(self.browseBtn) self.hbox1.addWidget(self.triggerBtn) self.browseBtn.clicked.connect(self.OpenFile) self.triggerBtn.clicked.connect(self.setupTypeThread) self.stopBtn.clicked.connect(self.threadStop) self.status = QTreeWidget(self) self.status.setHeaderHidden(True) self.hbox2.addWidget(self.status) self.hbox3.addWidget(self.table) self.hbox4.addWidget(self.stopBtn) self.setGeometry(200, 200, 700, 400) self.status.setFixedHeight (80) self.layout = QVBoxLayout() self.layout.addWidget(self.tableLabel) self.layout.addLayout(self.hbox1) self.layout.addLayout(self.hbox2) self.layout.addLayout(self.hbox3) self.layout.addLayout(self.hbox4) self.setLayout(self.layout) self.stopBtn.setEnabled(False)
def _copy(self): rows = sorted({ri.row() for ri in self.selectedIndexes()}) copy_object = [(ri, self._editor.value[ri]) for ri in rows] # copy_object = [ri.row(), self._editor.value[ri.row()]) for ri in self.selectedIndexes()] mt = self._editor.factory.mime_type pdata = dumps(copy_object) qmd = PyMimeData() qmd.MIME_TYPE = mt qmd.setData(unicode(mt), dumps(copy_object.__class__) + pdata) clipboard = QApplication.clipboard() clipboard.setMimeData(qmd)
def paste(self): if len(self.view.tableView.selectionModel().selectedIndexes()) == 0: return clipboard = QApplication.clipboard() index = self.view.tableView.selectionModel().selectedIndexes()[0] command = EditCommand(self.table_model, index) command.newValue(str(clipboard.text())) self.undo_stack.beginMacro("Paste") self.undo_stack.push(command) self.undo_stack.endMacro() self.set_undo_redo_text() self.view.tableView.reset()
def paste(self): if len(self.gui.tableView.selectionModel().selectedIndexes()) == 0: return clipboard = QApplication.clipboard() index = self.gui.tableView.selectionModel().selectedIndexes()[0] command = EditCommand(self.tbm, index) command.newVal(str(clipboard.text())) self.undoStack.beginMacro("Paste") self.undoStack.push(command) self.undoStack.endMacro() self.set_unrdo_text() self.gui.tableView.reset()
def __init__(self, parent=None): ''' Constructor ''' QMainWindow.__init__(self, parent) self.ui = Ui_ConsoleWindow() self.ui.setupUi(self) self.prompt_is_dirty = True self.regular_prompt = ">>> " self.more_prompt = "... " self.prompt = self.regular_prompt QApplication.clipboard().dataChanged.connect(self.onClipboardDataChanged) self.te = self.ui.plainTextEdit self.te.selectionChanged.connect(self.onSelectionChanged) self.te.cursorPositionChanged.connect(self.onCursorPositionChanged) self.append_blue("Welcome to the Cinemol python console!\n") # This header text is intended to look just like the standard python banner self.append_blue("Python " + sys.version + " on " + sys.platform) # self.append('Type "help", "copyright", "credits" or "license" for more information.') self.append("") # Need return before prompt # make cursor about the size of a letter cursor_size = QFontMetrics(self.te.font()).width("m") if cursor_size > 0: self.te.setCursorWidth(cursor_size) else: self.te.setCursorWidth(1) self.command_ring = CommandRing() self.multiline_command = "" self.te.installEventFilter(self) self.te.viewport().installEventFilter(self) self.command_buffer = "" self.current_command_start_position = None self.place_new_prompt() self.stdout = ConsoleStdoutStream(self) self.stderr = ConsoleStderrStream(self) self.stdin = ConsoleStdinStream(self) self.recent_files = recent_file.RecentFileList(self.run_script_file, "input_script_files", self.ui.menuOpen_recent)
def keyPressEvent(self, e): if e.matches(QKeySequence.Paste): clipboard = QApplication.clipboard() mimeData = clipboard.mimeData() if mimeData.hasImage(): image = clipboard.image() byteArray = QByteArray() buf = QBuffer(byteArray) buf.open(QIODevice.WriteOnly) image.save(buf, "PNG") self.label.setText('Uploading') self.thread = NetThread(str(byteArray.toBase64())) self.thread.finished.connect(self.onThreadEnd) self.thread.start() else: self.label.setText('No picture in clipboard')
def action_paste_cell(self): if self.cell_selected(): clipboard = QApplication.clipboard() index = self.view.tableView.selectionModel().selectedIndexes()[0] command = EditCommand(self.table_model, index) command.newValue(clipboard.text()) self.model.undo_stack.beginMacro("Paste Cell") self.model.undo_stack.push(command) self.model.undo_stack.endMacro() self.update_undo_actions() self.view.tableView.reset() return True else: # TODO return False
def gui_script(): try: app = QApplication(sys.argv) except NameError: # TODO: fix this long logger setup from cobaya.log import logger_setup, HandledException logger_setup(0, None) import logging logging.getLogger("cosmo_generator").error( "PySide or PySide2 is not installed! " "Check Cobaya's documentation for the cosmo_generator " "('Basic cosmology runs').") raise HandledException clip = app.clipboard() window = MainWindow() window.clipboard = clip sys.exit(app.exec_())
def _getClipboardObservations(self): text = QApplication.clipboard().text() docFormat = self.document.documentFormat if docFormat is None: self._handleEditError( 'Paste', 'Document has no format with which to parse clipboard text.') return None try: lines = text.strip().splitlines() return docFormat.parseDocument(lines) except ValueError, e: self._handleEditError( 'Paste', 'Attempt to parse clipboard text yielded the following error message:\n\n' + str(e)) return None
def copyRowToClipboard(self): clipboard = QApplication.clipboard() clipboard.setText("\t".join( [t.text() for t in self.table.selectedItems()]))
def copy_text(self, text): QApplication.clipboard().setText(text)
def paste_seed_words(self): text = QApplication.clipboard().text() self.on_paste_seed_words_event.emit(text)
def onThreadEnd(self): url = self.thread.getResult() self.edit.setText(url) QApplication.clipboard().setText(url) self.label.setText('Finish (URL in clipboard)')
def __init__(self, parent=None): super(mainwin, self).__init__(parent) self.setWindowTitle("Nigandu English to Tamil Dictionary") self.setGeometry(200, 50, 650, 600) self.setMinimumHeight(620) self.setMinimumWidth(650) self.setMaximumHeight(660) self.setMaximumWidth(800) #Setting up status bar self.myStatusBar = QStatusBar() self.myStatusBar.showMessage('Ready', 7000) self.setStatusBar(self.myStatusBar) #Setting up application icon appIcon = QIcon(":/icons/njnlogo.png") self.setWindowIcon(appIcon) # defining the central widget self.central = QWidget(self) #combobox plus search button self.whole = QVBoxLayout(self.central) self.gridlayout = QGridLayout() self.comboBox = QLineEdit(self) #self.comboBox.setEditable(True) self.comboBox.setObjectName("comboBox") self.completer = QCompleter(self.comboBox) self.completer.setCompletionMode(QCompleter.UnfilteredPopupCompletion) self.completer.setCaseSensitivity(Qt.CaseInsensitive) self.completer.setMaxVisibleItems(10) self.comboBox.setCompleter(self.completer) #self.comboBox.setCompleter() self.gridlayout.addWidget(self.comboBox, 1, 1, 1, 2) self.searchbtn = QPushButton() self.searchbtn.setObjectName("searchbtn") self.searchbtn.setText("&Search") self.gridlayout.addWidget(self.searchbtn, 1, 3) vbox = QVBoxLayout() self.tamtext = QTextBrowser() self.listview = QListWidget(self) #self.listview.setEditTriggers(QAbstractItemView.NoEditTriggers) self.listview.setWindowTitle("Suggested words") self.tamtext.setMinimumHeight(100) self.tamtext.setMaximumHeight(150) vbox.addWidget(self.tamtext) self.suglbl = QLabel(self) self.suglbl.setText("Suggested Words:") vbox.addWidget(self.suglbl) vbox.addWidget(self.listview) self.whole.addLayout(self.gridlayout) self.whole.addLayout(vbox) self.setCentralWidget(self.central) #setting docks self.histdockwidg = QDockWidget("History", self) self.bkmdockwidg = QDockWidget("Book Marks", self) self.histdockwidg.setObjectName("self.histdockwidg") self.bkmdockwidg.setObjectName("self.bkmdockwidg") #self.histdockwidg.setMaximumWidth(histwidth) self.histdockwidg.setAllowedAreas(Qt.RightDockWidgetArea) self.bkmdockwidg.setAllowedAreas(Qt.RightDockWidgetArea) self.histdockwidg.setMaximumWidth(250) self.bkmdockwidg.setMaximumWidth(250) self.histdockwidg.setMinimumWidth(200) self.bkmdockwidg.setMinimumWidth(200) #self.bkmdockwidg.setMaximumWidth(histwidth) self.histli = QListWidget() self.bkmli = QListWidget() self.histlis = [0] self.bkmlistfromfile = [] self.histdockwidg.setWidget(self.histli) self.bkmdockwidg.setWidget(self.bkmli) self.addDockWidget(Qt.RightDockWidgetArea, self.histdockwidg) self.addDockWidget(Qt.RightDockWidgetArea, self.bkmdockwidg) #file menu fi_addwrd = self.createactions("&Add a word...", self.addwrdf, "Alt+A", ":/icons/add.png", "Add a word to the dictionary. . .") fi_options = self.createactions("&Options", self.optionsf, "None", ":/icons/options.png", "Change the default settings. . .") fi_help = self.createactions("&Help", self.helpf, QKeySequence.HelpContents, ":/icons/help.png", "Help contents. . .") fi_quit = self.createactions("&Quit", self.close, QKeySequence.Close, ":/icons/quit.png", "Close the application. . .") fplus = self.createactions("FontPlus", self.fplusf, "None", ":/icons/fplus.png", "Increase the font size") fminus = self.createactions("FontMinus", self.fminusf, "None", ":/icons/fminus.png", "Decrease the font size") #list of file actions fi_menu = (fi_addwrd, fi_options, fi_help, None, fi_quit) #go menu self.go_prev = self.createactions("&Previous Word", self.prevf, "Alt+Z", ":/icons/prev.png", "Previous Word") self.go_next = self.createactions("&Next Word", self.nextf, "Alt+X", ":/icons/next.png", "Next Word") self.go_rand = self.createactions("&Random Word", self.randf, "Ctrl+R", ":/icons/rand.png", "Select a random word") #list of go actions go_menu = (self.go_prev, self.go_next, self.go_rand ) self.go_next.setEnabled(False) self.go_prev.setEnabled(False) #book mark menu self.bkm_addfav = self.createactions("&Bookmark", self.addfavf, "Ctrl+B", ":/icons/bookmark.png", "Book mark this word") self.bkm_viewbkm = self.createactions("&View Bookmarks", self.viewbkmf, "Alt+V", ":/icons/viewbkm.png", "View bookmarked words") #list of book mark items bkm_menu = (self.bkm_addfav, self.bkm_viewbkm) #help menu hlp_about = self.createactions("Abo&ut", self.aboutf, "Ctrl+U", ":/icons/about.png", "About") hlp_visitblog = self.createactions("&Visit Blog", self.visitblogf, "None", ":/icons/visitblog.png", "Visit our blog") hlp_help = self.createactions("&Help", self.helpf, "Ctrl+H", ":/icons/help.png", "Help Contents") #list of help menu items hlp_menu = (hlp_about, hlp_visitblog, hlp_help) #Setting up the menubar filemenu = self.menuBar().addMenu("&File") self.addmenu(filemenu, fi_menu) gomenu = self.menuBar().addMenu("&Go") self.addmenu(gomenu, go_menu) bkmmenu = self.menuBar().addMenu("&Book Mark") self.addmenu(bkmmenu, bkm_menu) helpmenu = self.menuBar().addMenu("&Help") self.addmenu(helpmenu, hlp_menu) intn = QSize(40, 40) self.setIconSize(intn) #Setting up the tool bar filetools = self.addToolBar("File") filetools.setObjectName("filetools") self.addmenu(filetools, (fi_addwrd, fplus, fminus)) gotools = self.addToolBar("Go") gotools.setObjectName("gotools") self.addmenu(gotools, go_menu) bkmtools = self.addToolBar("Bkm") bkmtools.setObjectName("bkmtools") self.addmenu(bkmtools, bkm_menu) hlptools = self.addToolBar("Help") hlptools.setObjectName("helptools") self.addmenu(hlptools, hlp_menu) self.loadfiles() self.returncount = 0 self.bkm_addfav.setEnabled(False) #clipboard function if self.clipauto: clip = QApplication.clipboard() cliptxt = clip.text() self.comboBox.setText(cliptxt) self.setevent() #connections self.connect(self.comboBox, SIGNAL("textChanged(QString)"), self.search) self.connect(self.comboBox, SIGNAL("returnPressed()"), self.returnpressedevent) self.connect(self.searchbtn, SIGNAL("clicked()"), self.onenter) self.connect(self.listview, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) self.connect(self.histli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall) self.connect(self.bkmli, SIGNAL("itemDoubleClicked(QListWidgetItem*)"), self.listwidcall)
def _copySelectionToClipboard(self): text = self._obsList.selectedText QApplication.clipboard().setText(text)
def putAddrInClipboard(self, addr): QApplication.clipboard().setText(addr, QClipboard.Clipboard)
def keyPressEvent ( self, e ): """ Handle user input a key at a time. """ text = e.text() if text.length() and (32 <= ord( text.toAscii()[0] ) < 127): self._insert_text( text ) return key = e.key() if e.matches( QKeySequence.Copy ): text = self.textCursor().selectedText() if not text.isEmpty(): QApplication.clipboard().setText( text ) elif e.matches( QKeySequence.Paste ): self._insert_text( QApplication.clipboard().text() ) elif key == Qt.Key_Backspace: if self._point: cursor = self.textCursor() cursor.deletePreviousChar() self.setTextCursor( cursor ) self._point -= 1 self._line.remove( self._point, 1 ) elif key == Qt.Key_Delete: cursor = self.textCursor() cursor.deleteChar() self.setTextCursor( cursor ) self._line.remove( self._point, 1 ) elif key in ( Qt.Key_Return, Qt.Key_Enter ): self.write( '\n' ) if self._reading: self._reading = False else: self.run( str( self._line ) ) elif key == Qt.Key_Tab: self._insert_text( text ) elif e.matches( QKeySequence.MoveToPreviousChar ): if self._point: self.moveCursor( QTextCursor.Left ) self._point -= 1 elif e.matches( QKeySequence.MoveToNextChar ): if self._point < self._line.length(): self.moveCursor( QTextCursor.Right ) self._point += 1 elif e.matches( QKeySequence.MoveToStartOfLine ): while self._point: self.moveCursor( QTextCursor.Left ) self._point -= 1 elif e.matches( QKeySequence.MoveToEndOfLine ): self.moveCursor( QTextCursor.EndOfBlock ) self._point = self._line.length() elif e.matches( QKeySequence.MoveToPreviousLine ): if len( self.history ): if self.historyIndex == 0: self.historyIndex = len( self.history ) self.historyIndex -= 1 self._recall() elif e.matches( QKeySequence.MoveToNextLine ): if len( self.history ): self.historyIndex += 1 if self.historyIndex == len( self.history ): self.historyIndex = 0 self._recall() else: e.ignore()
def _clipboard_default ( self ): """ Initialise the clipboard. """ return QApplication.clipboard()
class _TableView(TableView): """ for drag and drop reference see https://github.com/enthought/traitsui/blob/master/traitsui/qt4/tree_editor.py """ paste_func = None drop_factory = None # link_copyable = True copyable = True # _copy_cache = None # _linked_copy_cache = None _dragging = None _cut_indices = None option_select = False drag_enabled = True def __init__(self, editor, layout=None, *args, **kw): super(_TableView, self).__init__(editor, *args, **kw) self.setItemDelegate(ItemDelegate(self)) # self.setup_consumer(main=True) editor = self._editor # # reimplement row height vheader = self.verticalHeader() # size = vheader.minimumSectionSize() height = None font = editor.adapter.get_font(editor.object, editor.name, 0) if font is not None: fnt = QtGui.QFont(font) size = QtGui.QFontMetrics(fnt) height = size.height() + 6 vheader.setFont(fnt) hheader = self.horizontalHeader() hheader.setFont(fnt) if editor.factory.row_height: height = editor.factory.row_height if height: vheader.setDefaultSectionSize(height) else: vheader.ResizeMode(QHeaderView.ResizeToContents) def set_bg_color(self, bgcolor): if isinstance(bgcolor, tuple): if len(bgcolor) == 3: bgcolor = 'rgb({},{},{})'.format(*bgcolor) elif len(bgcolor) == 4: bgcolor = 'rgba({},{},{},{})'.format(*bgcolor) elif isinstance(bgcolor, QColor): bgcolor = 'rgba({},{},{},{})'.format(*bgcolor.toTuple()) self.setStyleSheet( 'QTableView {{background-color: {}}}'.format(bgcolor)) def set_vertical_header_font(self, fnt): fnt = QtGui.QFont(fnt) vheader = self.verticalHeader() vheader.setFont(fnt) size = QtGui.QFontMetrics(fnt) vheader.setDefaultSectionSize(size.height() + 6) def set_horizontal_header_font(self, fnt): fnt = QtGui.QFont(fnt) vheader = self.horizontalHeader() vheader.setFont(fnt) def set_drag_enabled(self, d): if d: self.setDragDropMode(QtGui.QAbstractItemView.DragDrop) self.setDragEnabled(True) def startDrag(self, actions): if self._editor.factory.drag_external: idxs = self.selectedIndexes() rows = sorted(list(set([idx.row() for idx in idxs]))) drag_object = [(ri, self._editor.value[ri]) for ri in rows] md = PyMimeData.coerce(drag_object) self._dragging = self.currentIndex() drag = QtGui.QDrag(self) drag.setMimeData(md) drag.exec_(actions) else: super(_TableView, self).startDrag(actions) def dragEnterEvent(self, e): if self.is_external(): # Assume the drag is invalid. e.ignore() # Check what is being dragged. ed = e.mimeData() md = PyMimeData.coerce(ed) if md is None: return elif not hasattr(ed.instance(), '__iter__'): return # We might be able to handle it (but it depends on what the final # target is). e.acceptProposedAction() else: super(_TableView, self).dragEnterEvent(e) def dragMoveEvent(self, e): if self.is_external(): e.acceptProposedAction() else: super(_TableView, self).dragMoveEvent(e) def dropEvent(self, e): if self.is_external(): data = PyMimeData.coerce(e.mimeData()).instance() if not hasattr(data, '__iter__'): return df = self.drop_factory if not df: df = lambda x: x row = self.rowAt(e.pos().y()) n = len(self._editor.value) if row == -1: row = n model = self._editor.model if self._dragging: rows = [ri for ri, _ in data] model.moveRows(rows, row) else: data = [di for _, di in data] with no_update(self._editor.object): for i, di in enumerate(reversed(data)): if isinstance(di, tuple): di = di[1] model.insertRow(row=row, obj=df(di)) for i, di in enumerate(reversed(df(data))): model.insertRow(row=row, obj=di) e.accept() self._dragging = None else: super(_TableView, self).dropEvent(e) def is_external(self): # print 'is_external', self._editor.factory.drag_external and not self._dragging return self._editor.factory.drag_external # and not self._dragging def keyPressEvent(self, event): if event.matches(QtGui.QKeySequence.Copy): # self._copy_cache = [self._editor.value[ci.row()] for ci in # self.selectionModel().selectedRows()] # self._copy_cache = self._get_selection() # self._editor.copy_cache = self._copy_cache self._cut_indices = None # add the selected rows to the clipboard self._copy() elif event.matches(QtGui.QKeySequence.Cut): self._cut_indices = [ ci.row() for ci in self.selectionModel().selectedRows() ] # self._copy_cache = [self._editor.value[ci] for ci in self._cut_indices] # self._copy_cache = self._get_selection(self._cut_indices) # self._editor.copy_cache = self._copy_cache elif event.matches(QtGui.QKeySequence.Paste): if self.pastable: self._paste() else: self._editor.key_pressed = TabularKeyEvent(event) self._key_press_hook(event) # private def _copy(self): rows = sorted({ri.row() for ri in self.selectedIndexes()}) copy_object = [(ri, self._editor.value[ri].tocopy()) for ri in rows] # copy_object = [ri.row(), self._editor.value[ri.row()]) for ri in self.selectedIndexes()] mt = self._editor.factory.mime_type try: pdata = dumps(copy_object) except BaseException, e: print 'tabular editor copy failed' self._editor.value[rows[0]].tocopy(verbose=True) return qmd = PyMimeData() qmd.MIME_TYPE = mt qmd.setData(unicode(mt), dumps(copy_object.__class__) + pdata) clipboard = QApplication.clipboard() clipboard.setMimeData(qmd)
def copy_to_clipboard(self): QApplication.clipboard().setText(self.password.text())
def gui_script(): app = QApplication(sys.argv) clip = app.clipboard() window = MainWindow() window.clipboard = clip sys.exit(app.exec_())
use_special_characters = True lower_case_letters = list('abcdefghijklmnopqrstuvwxyz') upper_case_letters = list('ABCDEFGHJKLMNPQRTUVWXYZ') digits = list('0123456789') special_characters = list('#!"ยง$%&/()[]{}=-_+*<>;:.') self.password_characters = [] if use_letters: self.password_characters += lower_case_letters + upper_case_letters if use_digits: self.password_characters += digits if use_special_characters: self.password_characters += special_characters def convert_bytes_to_password(self, digest, length): number = int.from_bytes(digest, byteorder='big') password = '' while number > 0 and len(password) < length: password = password + self.password_characters[number % len(self.password_characters)] number //= len(self.password_characters) return password def generate(self, master_password, domain, username='', length=10, iterations=4096): hash_string = domain + username + master_password hashed_bytes = pbkdf2_hmac('sha512', hash_string.encode('utf-8'), self.salt, iterations) return self.convert_bytes_to_password(hashed_bytes, length) app = QApplication(sys.argv) window = MainWindow(app.clipboard()) app.exec_()
def copyToClipboard(self): if not self.table.currentItem() is None: clipboard = QApplication.clipboard() clipboard.setText(self.table.currentItem().text())
def copy_table_view_to_csv(self, view: QTableView, special_headers=[], special_formatters=dict()): """ Copies the selected rows in the view to the clipboard Will use the Horse delegates if any (because they display information in a different way). :param view: :return: """ rows_ndx = self._selected_rows(view.selectedIndexes()) model = view.model() visible_cols = [] for c in range(model.columnCount()): if not view.isColumnHidden(c): visible_cols.append(c) s = "" if special_headers: h = special_headers else: h = [] mh = view.horizontalHeader().model() for col in visible_cols: h.append(mh.headerData(col, Qt.Horizontal, Qt.DisplayRole)) s += self._line_to_csv(h) for row in rows_ndx: r = [] for col in visible_cols: model_index = model.index(row, col) if col in special_formatters: formatted = special_formatters[col](model_index) if type(formatted) in (list, tuple): r += list(formatted) elif type(formatted) == float: r.append(format_csv(formatted)) else: r.append(str(formatted)) else: d = view.itemDelegateForColumn(col) if d: displayed_data = d.get_displayed_data(model_index) else: displayed_data = model_index.data(Qt.DisplayRole) if displayed_data and type(model_index.data( Qt.UserRole)) == float: # FIXME This a hack to convert float representations to # the convert decimal format for CSV pasting. Rmemeber that MS Excel # might have different decimal point, based on the locale... # This is sub optimal because a float might not always be represented # as a float... But it's not the case for now => not a problem. r.append(displayed_data.replace(u".", decimal_point)) else: r.append(displayed_data) s += self._line_to_csv(r) mainlog.debug("copy_table_view: {}".format(s)) QApplication.clipboard().setText(s)
def set_clipboard_html(self): """Place the HTML displayed in the HTML view widget into the system clipboard. """ data = QMimeData() data.setText(self.plain) data.setHtml(self.html) QApplication.clipboard().setMimeData(data)