def saveScreenshot(self, clipboard=False, fileName='screenshot.png', picType='png'): fullWindow = QRect(0, 0, self.width() - 1, self.height() - 1) selected = QRect(self.selected_area) if selected.left() < 0: selected.setLeft(0) if selected.right() >= self.width(): selected.setRight(self.width() - 1) if selected.top() < 0: selected.setTop(0) if selected.bottom() >= self.height(): selected.setBottom(self.height() - 1) source = (fullWindow & selected) source.setTopLeft( QPoint(source.topLeft().x() * self.scale, source.topLeft().y() * self.scale)) source.setBottomRight( QPoint(source.bottomRight().x() * self.scale, source.bottomRight().y() * self.scale)) image = self.screenPixel.copy(source) if clipboard: QGuiApplication.clipboard().setImage(image.toImage(), QClipboard.Clipboard) else: image.save(fileName, picType, 10) self.target_img = image self.target_img_pos = source self.screen_shot_grabed.emit(image.toImage()) self.screen_shot_pos_grabed.emit(source)
def copy(self): # ctrl+c data = { 'nodes': self.get_node_instances_json_data(self.selected_node_instances()), 'connections': self.get_connections_json_data(self.selected_node_instances()), 'drawings': self.get_drawings_json_data(self.selected_drawings()) } QGuiApplication.clipboard().setText(json.dumps(data))
def cut(self): # called from shortcut ctrl+x data = { 'nodes': self.get_node_instances_json_data(self.selected_node_instances()), 'connections': self.get_connections_json_data(self.selected_node_instances()), 'drawings': self.get_drawings_json_data(self.selected_drawings()) } QGuiApplication.clipboard().setText(json.dumps(data)) self.remove_selected_components()
def copy_clicked(self): index = self.copy_buttons.index(self.sender()) code_editor = list(self.code_update_assignments.keys())[index] code = code_editor.get_code() cb = QGuiApplication.clipboard() cb.clear(mode=cb.Clipboard) cb.setText(code)
def _paste(self): """ Pastes the clipboard contents to the scene. :return: """ md = QGuiApplication.clipboard().mimeData() ba = md.data("nexxT/json") if ba.count() > 0: logger.internal("Paste") cfg = json.loads(bytes(ba).decode()) nameTransformations = {} for n in cfg["nodes"]: nameTransformations[ n["name"]] = self.scene().graph.uniqueNodeName(n["name"]) n["name"] = nameTransformations[n["name"]] newConn = [] for c in cfg["connections"]: node1, port1, node2, port2 = SubConfiguration.connectionStringToTuple( c) node1 = nameTransformations[node1] node2 = nameTransformations[node2] newConn.append( SubConfiguration.tupleToConnectionString( (node1, port1, node2, port2))) cfg["connections"] = newConn def compositeLookup(name): return self.scene().graph.getSubConfig().getConfiguration( ).compositeFilterByName(name) self.scene().graph.getSubConfig().load(cfg, compositeLookup) self.scene().autoLayout() logger.info("Pasted")
def paste(self): data = {} try: data = json.loads(QGuiApplication.clipboard().text()) except Exception as e: return self.clear_selection() # calculate offset positions = [] for d in data['drawings']: positions.append({'x': d['pos x'], 'y': d['pos y']}) for n in data['nodes']: positions.append({'x': n['position x'], 'y': n['position y']}) offset_for_middle_pos = QPointF(0, 0) if len(positions) > 0: rect = QRectF(positions[0]['x'], positions[0]['y'], 0, 0) for p in positions: x = p['x'] y = p['y'] if x < rect.left(): rect.setLeft(x) if x > rect.right(): rect.setRight(x) if y < rect.top(): rect.setTop(y) if y > rect.bottom(): rect.setBottom(y) offset_for_middle_pos = self.last_mouse_move_pos - rect.center() self.undo_stack.push(Paste_Command(self, data, offset_for_middle_pos))
def __init__(self, nf_settings_path): super(batch_file_viewer, self).__init__(parent=None) self.nf_settings_parser = custom_config_parser() self.nf_settings_parser.load(nf_settings_path) self.setRowCount(20) self.setColumnCount(2) # Fill all places so there are no "None" types in the table for row in range(self.rowCount()): for column in range(self.columnCount()): item = QTableWidgetItem() item.setText('') self.setItem(row, column, item) self.original_background = item.background() self.clipboard = QGuiApplication.clipboard() self.cellChanged.connect( self.check_cell) # Needs to be after "filling for loop" above self.header = self.horizontalHeader() self.header.setSectionResizeMode(0, QHeaderView.Stretch) self.setHorizontalHeaderLabels(["MS files", "Label"]) self.header.setContextMenuPolicy(QtCore.Qt.CustomContextMenu) self.header.customContextMenuRequested.connect(self.right_click_menu) self.saved_text = '' self.store_re_text = ''
def _copy2clipboard(self): """ kopiert die angezeigte Zahl ins Clipboard :return: """ clipboard = QGuiApplication.clipboard() clipboard.setText(self._sumLabel.text())
def _copyText(self): """Copies the selected item text to the clipboad """ selectedItem = self._selectedItems() if selectedItem: selectedItem = selectedItem[0] # get the clipboard clipboard = QGuiApplication.clipboard() # set the text clipboard.setText(selectedItem.text(0))
def _copy(self, cut): """ Copys the selection to clipboard. :param cut: boolean whether the copy is actually a cut. :return: """ logger.internal("Copying...") sc = self.scene() assert isinstance(sc, GraphScene) items = sc.selectedItems() nodes = set() for i in items: if isinstance(i, BaseGraphScene.NodeItem): nodes.add(i.name) saved = sc.graph.getSubConfig().save() if "_guiState" in saved: del saved["_guiState"] toDelIdx = [] deletedNodes = set() for i, n in enumerate(saved["nodes"]): if not n["name"] in nodes: toDelIdx.append(i) deletedNodes.add(n["name"]) for i in toDelIdx[::-1]: saved["nodes"] = saved["nodes"][:i] + saved["nodes"][i + 1:] cToDel = set() for c in saved["connections"]: node1, _, node2, _ = SubConfiguration.connectionStringToTuple(c) if node1 in deletedNodes or node2 in deletedNodes: cToDel.add(c) for c in cToDel: saved["connections"].remove(c) md = QMimeData() md.setData("nexxT/json", json.dumps(saved, indent=2, ensure_ascii=False).encode()) QGuiApplication.clipboard().setMimeData(md) if cut: for n in saved["nodes"]: sc.graph.deleteNode(n["name"]) logger.info("Copyied %d nodes and %d connections", len(saved["nodes"]), len(saved["connections"]))
def keyPressEvent(self, event): """ copied from https://stackoverflow.com/a/40473855 """ if event.matches(QKeySequence.Copy): selection = self.table.selectedIndexes() if selection: rows = sorted(index.row() for index in selection) columns = sorted(index.column() for index in selection) rowCount = rows[-1] - rows[0] + 1 colCount = columns[-1] - columns[0] + 1 table = [[''] * colCount for _ in range(rowCount)] for index in selection: row = index.row() - rows[0] column = index.column() - columns[0] table[row][column] = index.data() stream = io.StringIO() csv.writer(stream, delimiter='\t').writerows(table) QGuiApplication.clipboard().setText(stream.getvalue()) super().keyPressEvent(event)
def pointerEvent(self, event): """ Callback function that uses the pointer position to find the image coordinates and puts it in the system clipboard """ pointer = event.pointer() # The name of the image in the sequence for rv sourceName = commands.sourceAtPixel(pointer)[0]['name'] # Tuple containing the coordinates of the point event with regards to the image, # where the lower left corner of the image is (0,0) imgPointerCoords = commands.eventToImageSpace(sourceName, pointer) # An array of image attribute name/value pairs at the current frame imgAttributes = commands.sourceAttributes(sourceName) try: coords, locations = obtainQuadrantData(imgAttributes) except TypeError: return # We need to find the pixel value of the image height highestPixelValue = findHighestYPixel(coords) # We then convert the RV pointer data to pixels pointerPixelCoords = getPointerPixelValue(imgPointerCoords, highestPixelValue) found_location = matchPointerToLocation(coords, locations, pointerPixelCoords) print(found_location) # Copy the matched location to the clipboard QGuiApplication.clipboard().setText(found_location) # Display the copied data extra_commands.displayFeedback2( "Copied to clipboard: {}".format(found_location), 2.0)
def __init__(self): self.ui = QUiLoader().load('translator.ui') self.ms = MySignal() self.clipboard = QGuiApplication.clipboard() # 默认谷歌翻译、源语言自动识别、目标语言中文 self.engine = engines['谷歌翻译'] self.from_lang = 'auto' self.to_lang = 'zh-CN' self.to_langs = self.engine.to_langs self.clipboard.dataChanged.connect(self.automatically_translate) self.ui.pushButton.clicked.connect(self.manually_translate) self.ms.text_print.connect(self.print_to_gui) self.ui.comboBox.currentIndexChanged.connect(self.check_options) self.ui.comboBox_3.currentIndexChanged.connect(self.check_options)
def _onCopy( self, action:QAction, point:QPoint ): values:str = "" indexes = self._tv.selectedIndexes() row = -1 for idx in indexes: if row == -1: row = idx.row() if row != idx.row(): values += "\n" row = idx.row() elif len( values ) > 0: values += "\t" val = self._tv.model().data( idx, Qt.DisplayRole ) val = "" if not val else val if isinstance( val, Number ): values += str( val ) else: values += val #print( idx.row(), "/", idx.column(), ": ", val ) #print( "valuestring: ", values ) clipboard = QGuiApplication.clipboard() clipboard.setText( values )
def copy_button_clicked(self,button): clipboard = QGuiApplication.clipboard() self.button=button if self.button==self.copy_button_1: clipboard.setText(self.label_1.text()) elif self.button==self.copy_button_2: clipboard.setText(self.label_2.text()) elif self.button==self.copy_button_3: clipboard.setText(self.label_3.text()) elif self.button==self.copy_button_4: clipboard.setText(self.label_4.text()) elif self.button==self.copy_button_5: clipboard.setText(self.label_5.text())
def paste_button_clicked(self, button): clipboard = QGuiApplication.clipboard() self.button = button if self.button == self.paste_button_1: self.label_1.setText(clipboard.text()) elif self.button == self.paste_button_2: self.label_2.setText(clipboard.text()) elif self.button == self.paste_button_3: self.label_3.setText(clipboard.text()) elif self.button == self.paste_button_4: self.label_4.setText(clipboard.text()) elif self.button == self.paste_button_5: self.label_5.setText(clipboard.text())
def _copy_to_clipboard(content: str) -> None: clipboard = QGuiApplication.clipboard() clipboard.setText(content, QClipboard.Clipboard) if clipboard.supportsSelection(): clipboard.setText(content, QClipboard.Selection)
def copyImageSrc(self, image): clipboard = QGuiApplication.clipboard() clipboard.setImage(image)
def mouseDoubleClickEvent(self, event): clipboard = QGuiApplication.clipboard() clipboard.setText(self.format.strip()) self.console.system_alert('驗證碼已經複製到剪貼簿')
def copyImageFile(self, filename): clipboard = QGuiApplication.clipboard() image = QImage(filename) data = QMimeData() data.setImageData(image) clipboard.setMimeData(data)
def copyText(self, text): clipboard = QGuiApplication.clipboard() clipboard.setText(text)
def eventFilter(self, obj, event): if event.type() == QEvent.KeyPress: if event.key() == Qt.Key_Delete: self.remove_selected_rows() return True elif event.matches(QKeySequence.Copy): s_model = self.table_view.selectionModel() if s_model.hasSelection(): selection_range = s_model.selection().constFirst() table_str = "" clipboard = QGuiApplication.clipboard() for i in range(selection_range.top(), selection_range.bottom() + 1): row_value = [] for j in range(selection_range.left(), selection_range.right() + 1): row_value.append(s_model.model().index(i, j).data()) table_str += "\t".join(row_value) + "\n" clipboard.setText(table_str) return True elif event.matches(QKeySequence.Paste): s_model = self.table_view.selectionModel() if s_model.hasSelection(): clipboard = QGuiApplication.clipboard() table_str = clipboard.text() table_rows = table_str.splitlines( ) # splitlines avoids an empty line at the end selection_range = s_model.selection().constFirst() first_row = selection_range.top() first_col = selection_range.left() last_col_idx = 0 last_row_idx = 0 for i in range(len(table_rows)): model_i = first_row + i if model_i < self.model.rowCount(): row_cols = table_rows[i].split("\t") for j in range(len(row_cols)): model_j = first_col + j if model_j < self.model.columnCount(): self.model.setData( self.model.index(model_i, model_j), row_cols[j], Qt.EditRole) if model_j > last_col_idx: last_col_idx = model_j if model_i > last_row_idx: last_row_idx = model_i first_index = self.model.index(first_row, first_col) last_index = self.model.index(last_row_idx, last_col_idx) self.model.dataChanged.emit(first_index, last_index) return True else: return QObject.eventFilter(self, obj, event) else: return QObject.eventFilter(self, obj, event) return QObject.eventFilter(self, obj, event)
def copy(self): QGuiApplication.clipboard().setText(self.fileNameLabel.text())
def __init__(self, parent=None): try: super().__init__(parent) loader = QUiLoader() file = QFile(os.path.abspath("forms/MainWindow.ui")) file.open(QFile.ReadOnly) ui = loader.load(file, self) file.close() self.setLayout(ui.layout()) # Components self.clipboard = QGuiApplication.clipboard() self.desktop = QDesktopWidget() self.trans_label = self.findChild(QLabel, "transLabel") self.transparent_slider = self.findChild(QSlider, "transparentSlider") self.interface_frame = self.findChild(QFrame, "interfaceFrame") self.hide_button = self.findChild(QPushButton, "hideButton") self.enable_box = self.findChild(QCheckBox, "enableBox") self.on_top_box = self.findChild(QCheckBox, "onTopBox") self.clear_button = self.findChild(QPushButton, "clearButton") self.system_tray = SystemTray(self) self.currentScreen = 0 self.currentPosition = 0 self.is_on_top = True self.is_enable = True self.is_show_panel = True self.is_not_fixed = True self.is_grab = False self.is_follow_cursor = False # Instances self.config = config_parser.Configuration() self.trans_request = web_api.YouDaoRequest(self.config) self.translate_thread = threads.TranslatorThread( self.config, self.trans_request, self.get_clip_text, self) # initialize self._initialize() # self.trans_label.setAttribute(QtCore.Qt.WA_TransparentForMouseEvents, True); # register QObject.connect(self.enable_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_enabled(int)")) QObject.connect(self.on_top_box, SIGNAL("stateChanged(int)"), self, SLOT("_set_on_top(int)")) QObject.connect(self.translate_thread, SIGNAL("finished()"), self, SLOT("_translate()")) QObject.connect(self.transparent_slider, SIGNAL("valueChanged(int)"), self, SLOT("_set_transparent(int)")) QObject.connect(self.clipboard, SIGNAL("dataChanged()"), self, SLOT("translate()")) QObject.connect(self.desktop, SIGNAL("resized(int)"), self, SLOT("_set_geometry()")) QObject.connect(self.hide_button, SIGNAL("clicked()"), self, SLOT("hide_interface()")) except TranslatorException as e: err_box = QMessageBox(self.parent()) err_box.setText(str(e)) err_box.exec_() sys.exit(-1)