def copySelection(self): """ This function copies the selected cells in a table view, accounting for filters and rows as well as non-continuous selection ranges. The format of copied values can be pasted into Excel retaining the original organization. Adapted from code provided by ekhumoro on StackOverflow https://stackoverflow.com/questions/40469607/ how-to-copy-paste-multiple-items-form-qtableview- created-by-qstandarditemmodel/40473855#40473855 """ selection = self.selectedIndexes() if selection: rows = [index.row() for index in selection] columns = [index.column() for index in selection] rowCount = max(rows) - min(rows) + 1 colCount = max(columns) - min(columns) + 1 table = [[""] * colCount for _ in range(rowCount)] for index in selection: row = index.row() - min(rows) column = index.column() - min(columns) table[row][column] = index.data() stream = io.StringIO() csv.writer(stream, delimiter="\t").writerows(table) QApplication.clipboard().setText(stream.getvalue())
def copy(self): """Copy current selection to clipboard in excel format.""" selection = self.selectionModel().selection() if not selection: return False v_header = self.verticalHeader() h_header = self.horizontalHeader() row_dict = {} for rng in sorted(selection, key=lambda x: h_header.visualIndex(x.left())): for i in range(rng.top(), rng.bottom() + 1): if v_header.isSectionHidden(i): continue row = row_dict.setdefault(i, []) for j in range(rng.left(), rng.right() + 1): if h_header.isSectionHidden(j): continue data = self.model().index(i, j).data(Qt.EditRole) if data is not None: try: number = float(data) str_data = locale.str(number) except ValueError: str_data = str(data) else: str_data = "" row.append(str_data) with io.StringIO() as output: writer = csv.writer(output, delimiter="\t", quotechar="'") for key in sorted(row_dict): writer.writerow(row_dict[key]) QApplication.clipboard().setText(output.getvalue()) return True
def hCopy(self): """ # slot for action copy_to_clipboard """ sel = self.listWdg.selectedItems() #################### # test code l = [] for item in sel: # get url from path l.append(QUrl.fromLocalFile(item.data(Qt.UserRole)[0])) # init clipboard data q = QMimeData() # set some Windows magic values for copying files from system clipboard : Don't modify # 1 : copy; 2 : move q.setData("Preferred DropEffect", QByteArray(1, "2")) q.setUrls(l) # end of test code ##################### # copy image to clipboard item = sel[0] filename = item.data(Qt.UserRole)[0] if filename.endswith(IMAGE_FILE_EXTENSIONS): q.setImageData(QImage(sel[0].data(Qt.UserRole)[0])) QApplication.clipboard().clear() QApplication.clipboard().setMimeData(q)
def copy(self): """Copy current selection to clipboard in CSV format.""" selection_model = self.selectionModel() if not selection_model.hasSelection(): return False selected_indexes = sorted(selection_model.selectedIndexes(), key=lambda index: 2 * index.row() + index.column()) row_first = selected_indexes[0].row() row_last = selected_indexes[-1].row() row_count = row_last - row_first + 1 data_indexes = row_count * [None] data_values = row_count * [None] data_model = self.model() for selected_index in selected_indexes: data = data_model.data(selected_index) row = selected_index.row() if selected_index.column() == 0: data_indexes[row - row_first] = data else: data_values[row - row_first] = data with io.StringIO() as output: writer = csv.writer(output, delimiter='\t') if all(stamp is None for stamp in data_indexes): for value in data_values: writer.writerow([locale.str(value) if value is not None else ""]) elif all(value is None for value in data_values): for index in data_indexes: writer.writerow([index if index is not None else ""]) else: for index, value in zip(data_indexes, data_values): index = index if index is not None else "" value = locale.str(value) if value is not None else "" writer.writerow([index, value]) QApplication.clipboard().setText(output.getvalue()) return True
async def _show_dialog_for_prime3_layout(self): from randovania.games.patchers import gollop_corruption_patcher patches = self.layout_description.all_patches[ self.current_player_index] game = default_database.game_description_for(RandovaniaGame.PRIME3) item_names = [] for index in range(game.world_list.num_pickup_nodes): p_index = PickupIndex(index) if p_index in patches.pickup_assignment: name = patches.pickup_assignment[p_index].pickup.name else: name = "Missile Expansion" item_names.append(name) layout_string = gollop_corruption_patcher.layout_string_for_items( item_names) starting_location = patches.starting_location commands = "\n".join([ f'set seed="{layout_string}"', f'set "starting_items={gollop_corruption_patcher.starting_items_for(patches.starting_items)}"', f'set "starting_location={gollop_corruption_patcher.starting_location_for(starting_location)}"', ]) message_box = QtWidgets.QMessageBox(QtWidgets.QMessageBox.Information, "Commands for patcher", commands) common_qt_lib.set_default_window_icon(message_box) message_box.setTextInteractionFlags(Qt.TextSelectableByMouse) QApplication.clipboard().setText(commands) await async_dialog.execute_dialog(message_box)
def advance_line(self): if self.current_file is None: return try: line = self.current_file.readline() except Exception as exc: message_box = QMessageBox( parent=self, text=f"Failed to read:\n{type(exc).__name__}: {exc}", icon=QMessageBox.Critical) message_box.setInformativeText("Close the file?") message_box.setStandardButtons(QMessageBox.No | QMessageBox.Yes) message_box.setDefaultButton(QMessageBox.Yes) if message_box.exec_() == QMessageBox.Yes: self.cleanup() return if not line: return self.line_count += 1 self.line_counter.setText(str(self.line_count)) QApplication.clipboard().setText(line.rstrip("\n")) self.text_box.setPlainText(line + self.text_box.toPlainText())
def _menuAction_copy_evaluated_buffer(self, buffer_id): mime = QMimeData() buff = self.current_state.symbolic_buffers[buffer_id][0] res = self.current_state.solver.evaluate(buff).as_bytes() res = '"' + repr(res)[2:-1] + '"' mime.setText(res) QApplication.clipboard().setMimeData(mime)
def copy(self): """Copy current selection to clipboard in Excel compatible csv format.""" selection = self.selectionModel().selection() if not selection: return False top, bottom, left, right = _range(selection) model = self.model() out_table = list() for y in range(top, bottom + 1): row = (right - left + 1) * [None] for x in range(left, right + 1): index = model.index(y, x) if not selection.contains(index): continue data = index.data(Qt.EditRole) try: number = float(data) str_data = locale.str(number) except ValueError: str_data = str(data) except TypeError: if isinstance(data, IndexedValue): str_data = to_database(data) else: str_data = str(data) row[x - left] = str_data out_table.append(row) with io.StringIO() as output: writer = csv.writer(output, delimiter="\t", quotechar="'") writer.writerows(out_table) QApplication.clipboard().setText(output.getvalue()) return True
def copy_download_link_button(self): data = self.ui.listAppsWidget.currentItem().data(Qt.UserRole) QApplication.clipboard().setText( metadata.url(data['internal_name'], repo=HOST)) self.status_message( f"Copied the download link for \"{data['display_name']}\" to clipboard" )
def do_action(self, elem): row_number = self.index.row() value = None if elem.text() == "Web": value = self.tabla_cuentas.item(row_number, 1) if value is not None: value = value.text() elif elem.text() == "Usuario": value = self.tabla_cuentas.item(row_number, 2) if value is not None: value = value.text() elif elem.text() == "Contraseña": item_id = self.tabla_cuentas.item(row_number, 5) if item_id is not None: item_id = item_id.text() for entry in self.cuentas: if int(entry[0]) == int(item_id): value = entry[4] break elif elem.text() == "Ir a web": web = self.tabla_cuentas.item(row_number, 1) if web is not None: web = web.text() webbrowser.open(web) if value is not None: QApplication.clipboard().setText(value) self.status.showMessage( "Copiado al portapapeles, se limpiará en 20 segundos", 5000) QTimer.singleShot(20000, self.clearClipboard)
def get_screenshot(self: 'QMainWindow', name='shot.png', type_='png', do_display=True, disp_ops=None): """Grad a screenshot of the main window, save to file, and then copy to clipboard. Args: self (QMainWindow): Window to take the screenshot of. name (str): File to save the screenshot to. Defaults to 'shot.png'. type (str): Type of file to save. Defaults to 'png'. do_display (bool): True to display the file. Defaults to True. disp_ops (dict): Disctionary of options. Defaults to None. """ from PySide2.QtWidgets import QApplication, QMainWindow path = Path(name).resolve() # just grab the main window screenshot = self.grab() # type: QtGui.QPixelMap screenshot.save(str(path), type_) # Save QApplication.clipboard().setPixmap(screenshot) # To clipboard #print(f'Screenshot copied to clipboard and saved to:\n {path}') if do_display: _disp_ops = dict(width=500) _disp_ops.update(disp_ops or {}) display(Image(filename=str(path), **_disp_ops))
def paste(self): """Pastes data from clipboard.""" selection_model = self.selectionModel() if not selection_model.hasSelection(): return False clipboard = QApplication.clipboard() mime_data = clipboard.mimeData() data_formats = mime_data.formats() if 'text/plain' not in data_formats: return False try: pasted_table = self._read_pasted_text(QApplication.clipboard().text()) except ValueError: return False if isinstance(pasted_table, tuple): # Always use the first column pasted_table = pasted_table[0] paste_length = len(pasted_table) first_row, last_row, _, _ = _range(selection_model.selection()) selection_length = last_row - first_row + 1 model = self.model() model_row_count = model.rowCount() - 1 if selection_length == 1: # If a single row is selected, we paste everything. if model_row_count <= first_row + paste_length: model.insertRows(model_row_count, paste_length - (model_row_count - first_row)) elif paste_length > selection_length: # If multiple row are selected, we paste what fits the selection. paste_length = selection_length pasted_table = pasted_table[0:selection_length] indexes_to_set, values_to_set = self._paste_to_values_column(pasted_table, first_row, paste_length) model.batch_set_data(indexes_to_set, values_to_set) self._select_pasted(indexes_to_set) return True
def setUp(self): QApplication.clipboard().clear() self._table_view = TimeSeriesFixedResolutionTableView(parent=None) series = TimeSeriesFixedResolution("2019-08-08T15:00", "1h", [1.1, 2.2, 3.3, 4.4], False, False) model = TimeSeriesModelFixedResolution(series) self._table_view.setModel(model)
def copy_selection(self): selection = self.tableWidget1.selectedIndexes() if selection: rows = sorted(index.row() for index in selection) columns = range(len(self.widget_col_names)) rowcount = rows[-1] - rows[0] + 1 colcount = columns[-1] - columns[0] + 1 + 1 table = [[''] * colcount for _ in range(rowcount + 1)] table[0] = [] for i in range(len(self.widget_col_names)): text_to_add = self.widget_col_names[ i] + '/(' + self.widget_col_units[i] + ')' table[0] += [text_to_add] for index in selection: row = index.row() - rows[0] column = index.column() - columns[0] table[row + 1][column] = index.data().replace( chr(34), '' ) # ensure string can be read as csv by removing quotation mark (ascii character 34) table = table + [['T=' + self.temp_text.placeholderText()] + ['' for _ in range(colcount - 1)]] stream = io.StringIO() csv.writer(stream, delimiter=';', quoting=csv.QUOTE_NONE).writerows(table) QApplication.clipboard().setText(stream.getvalue())
def copy_input(self): """Copy only input.""" if not self._control.hasFocus(): return text = self._control.textCursor().selection().toPlainText() if not text: return # Remove prompts. lines = text.splitlines() useful_lines = [] for line in lines: m = self._highlighter._classic_prompt_re.match(line) if m: useful_lines.append(line[len(m.group(0)):]) continue m = self._highlighter._ipy_prompt_re.match(line) if m: useful_lines.append(line[len(m.group(0)):]) continue text = '\n'.join(useful_lines) try: was_newline = text[-1] == '\n' except IndexError: was_newline = False if was_newline: # user doesn't need newline text = text[:-1] QApplication.clipboard().setText(text)
def __init__(self, model: Model) -> None: super().__init__() self.model = model self.setWindowTitle(getTitleString('Mod Manager')) self.setMinimumSize(QSize(750, 500)) self.setupMenu() settings = QSettings() if settings.value('mainWindowGeometry'): self.restoreGeometry( settings.value('mainWindowGeometry')) # type: ignore if settings.value('mainWindowState'): self.restoreState( settings.value('mainWindowState')) # type: ignore # TODO: enhancement: add an url handler for 'nxm://' urls # see https://docs.microsoft.com/en-us/previous-versions/windows/internet-explorer/ie-developer/platform-apis/aa767914(v=vs.85) # noqa # TODO: enhancement: import settings from the witcher 3 mod manager QApplication.clipboard().dataChanged.connect( self.copyBufferChangedEvent) self.mainwidget = MainWidget(self, model) self.setCentralWidget(self.mainwidget) self.show() self.raise_() self.activateWindow()
def test_paste_single_localized_number(self): view = CopyPasteTableView() model = _MockModel() view.setModel(model) view.setCurrentIndex(model.index(0, 2)) QApplication.clipboard().setText(locale.str(-1.1)) self.assertTrue(view.paste()) self.assertEqual(model.index(0, 2).data(), "-1.1")
def copyToClipboard(str): '''Copies str argument to clipboard ''' #import PySide.QtGui as qtg #app = qtg.QApplication.instance() #clipboard = app.clipboard() #clipboard.setText(str) from PySide2.QtWidgets import QApplication QApplication.clipboard().setText(str)
def copy_url(self, checked=False): """Copy db url to clipboard.""" self._update_sa_url() if not self._sa_url: return self._sa_url.password = None QApplication.clipboard().setText(str(self._sa_url)) self._logger.msg.emit( f"Database url <b>{self._sa_url}</b> copied to clipboard")
def _copy_string(self, expr): mime = QMimeData() expr_bytes = split_bv_in_list(expr, 8) res = "" for el in reversed(expr_bytes): res += chr(el.value) if el.value >= 32 and el.value <= 126 else "." mime.setText(res) QApplication.clipboard().setMimeData(mime)
def _copy_little_endian(self, expr): mime = QMimeData() expr_bytes = split_bv_in_list(expr, 8) res = 0 i = 0 for el in reversed(expr_bytes): res += el.value << i * 8 i += 1 mime.setText(hex(res)) QApplication.clipboard().setMimeData(mime)
def _copy_binary(self, expr): mime = QMimeData() expr_bytes = split_bv_in_list(expr, 8) res = "\"" for el in reversed(expr_bytes): res += "\\x{:02x}".format(el.value) res += "\"" mime.setText(res) QApplication.clipboard().setMimeData(mime)
def test_paste_value_when_time_stamp_is_selected(self): selection_model = self._table_view.selectionModel() model = self._table_view.model() selection_model.select(model.index(0, 0), QItemSelectionModel.Select) copied_data = locale.str(-1.1) QApplication.clipboard().setText(copied_data) self._table_view.paste() series = TimeSeriesFixedResolution("2019-08-08T15:00", "1h", [-1.1, 2.2, 3.3, 4.4], False, False) self.assertEqual(model.value, series)
def copy(self): """Copy current selection to clipboard in excel format.""" selection = self.selectionModel().selection() if not selection: return False indexes = selection.indexes() values = [index.data(Qt.EditRole) for index in indexes] content = "\n".join(values) QApplication.clipboard().setText(content) return True
def test_paste_single_localized_row(self): view = CopyPasteTableView() model = _MockModel() view.setModel(model) selection_model = view.selectionModel() selection_model.select(model.index(0, 0), QItemSelectionModel.Rows | QItemSelectionModel.Select) QApplication.clipboard().setText("A\tB\t{}".format(locale.str(-1.1))) self.assertTrue(view.paste()) self.assertEqual(model.index(0, 0).data(), "A") self.assertEqual(model.index(0, 1).data(), "B") self.assertEqual(model.index(0, 2).data(), "-1.1")
def test_pasting_to_last_row_expands_model(self): selection_model = self._table_view.selectionModel() model = self._table_view.model() selection_model.select(model.index(3, 1), QItemSelectionModel.Select) copied_data = locale.str(-4.4) + '\n' + locale.str(-5.5) QApplication.clipboard().setText(copied_data) self._table_view.paste() series = TimeSeriesFixedResolution("2019-08-08T15:00", "1h", [1.1, 2.2, 3.3, -4.4, -5.5], False, False) self.assertEqual(model.value, series)
def test_paste_to_larger_selection_overrides_first_rows_only(self): selection_model = self._table_view.selectionModel() model = self._table_view.model() selection_model.select(model.index(0, 1), QItemSelectionModel.Select) selection_model.select(model.index(1, 1), QItemSelectionModel.Select) copied_data = locale.str(-1.1) QApplication.clipboard().setText(copied_data) self._table_view.paste() series = TimeSeriesFixedResolution("2019-08-08T15:00", "1h", [-1.1, 2.2, 3.3, 4.4], False, False) self.assertEqual(model.value, series)
def test_copy_db_url_to_clipboard(self): """Test that the database url from current selections is copied to clipboard.""" QApplication.clipboard().clear() self.ds.activate() self.ds_properties_ui.pushButton_create_new_spine_db.click() self.ds_properties_ui.toolButton_copy_url.click() # noinspection PyArgumentList clipboard_text = QApplication.clipboard().text() expected_url = "sqlite:///" + os.path.join(self.ds.data_dir, "DS.sqlite") self.assertEqual(expected_url, clipboard_text.strip())
def test_pasted_cells_are_selected(self): selection_model = self._table_view.selectionModel() model = self._table_view.model() selection_model.select(model.index(0, 1), QItemSelectionModel.Select) copied_data = locale.str(-1.1) + '\n' + locale.str(-2.2) QApplication.clipboard().setText(copied_data) self._table_view.paste() selected_indexes = selection_model.selectedIndexes() self.assertEqual(len(selected_indexes), 2) self.assertTrue(model.index(0, 1) in selected_indexes) self.assertTrue(model.index(1, 1) in selected_indexes)
def copyOTP(self): """ Copy text to clipboard """ # Current row intCurrRow = self.tblKeys.currentRow() print("current row " + str(intCurrRow)) str2FA = self.tblKeys.item(intCurrRow,2) QApplication.clipboard().setText(str2FA.text())
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!")