def copy(self): """Copy text to clipboard... or keyboard interrupt""" if self.hasSelectedText(): text = self.selectedText() text = text.replace('>>> ', '').replace('... ', '').strip() # removing prompts QApplication.clipboard().setText(text) else: raise KeyboardInterrupt
def copySelectedResults(self): if len(self.viewResult.selectedIndexes()) <= 0: return model = self.viewResult.model() # convert to string using tab as separator text = model.headerToString("\t") for idx in self.viewResult.selectionModel().selectedRows(): text += "\n" + model.rowToString(idx.row(), "\t") QApplication.clipboard().setText(text, QClipboard.Selection) QApplication.clipboard().setText(text, QClipboard.Clipboard)
def contextMenuEvent(self, e): menu = QMenu(self) subMenu = QMenu(menu) titleHistoryMenu = QCoreApplication.translate("PythonConsole", "Command History") subMenu.setTitle(titleHistoryMenu) subMenu.addAction( QCoreApplication.translate("PythonConsole", "Show"), self.showHistory, 'Ctrl+Shift+SPACE') subMenu.addSeparator() subMenu.addAction( QCoreApplication.translate("PythonConsole", "Save"), self.writeHistoryFile) subMenu.addSeparator() subMenu.addAction( QCoreApplication.translate("PythonConsole", "Clear File"), self.clearHistory) subMenu.addAction( QCoreApplication.translate("PythonConsole", "Clear Session"), self.clearHistorySession) menu.addMenu(subMenu) menu.addSeparator() copyAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Copy"), self.copy, QKeySequence.Copy) pasteAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Paste"), self.paste, QKeySequence.Paste) copyAction.setEnabled(False) pasteAction.setEnabled(False) if self.hasSelectedText(): copyAction.setEnabled(True) if QApplication.clipboard().text(): pasteAction.setEnabled(True) menu.exec_(self.mapToGlobal(e.pos()))
def clicked(self, pt, b): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard.''' if settings.captureShowLocation: if self.marker is None: self.marker = QgsVertexMarker(self.canvas) self.marker.setIconSize(18) self.marker.setPenWidth(2) self.marker.setIconType(QgsVertexMarker.ICON_CROSS) self.marker.setCenter(pt) else: self.removeMarker(); try: if self.capture4326: canvasCRS = self.canvas.mapSettings().destinationCrs() transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance()) pt4326 = transform.transform(pt.x(), pt.y()) self.capturesig.emit(pt4326) return msg = self.formatCoord(pt, self.settings.delimiter) formatString = self.coordFormatString() if msg != None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage("", "{} coordinate {} copied to the clipboard".format(formatString, msg), level=Qgis.Info, duration=4) except Exception as e: self.iface.messageBar().pushMessage("", "Invalid coordinate: {}".format(e), level=Qgis.Warning, duration=4)
def doCopyAll(self): output = '' for r in range(self.rasterInfoList.count()): output += self.rasterInfoList.item(r).text() + "\n" if output: clipboard = QApplication.clipboard() clipboard.setText(output)
def contextMenuEvent(self, e): menu = QMenu(self) subMenu = QMenu(menu) titleHistoryMenu = QCoreApplication.translate("PythonConsole", "Command History") subMenu.setTitle(titleHistoryMenu) subMenu.addAction(QCoreApplication.translate("PythonConsole", "Show"), self.showHistory, 'Ctrl+Shift+SPACE') subMenu.addSeparator() subMenu.addAction(QCoreApplication.translate("PythonConsole", "Save"), self.writeHistoryFile) subMenu.addSeparator() subMenu.addAction( QCoreApplication.translate("PythonConsole", "Clear File"), self.clearHistory) subMenu.addAction( QCoreApplication.translate("PythonConsole", "Clear Session"), self.clearHistorySession) menu.addMenu(subMenu) menu.addSeparator() copyAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Copy"), self.copy, QKeySequence.Copy) pasteAction = menu.addAction( QCoreApplication.translate("PythonConsole", "Paste"), self.paste, QKeySequence.Paste) copyAction.setEnabled(False) pasteAction.setEnabled(False) if self.hasSelectedText(): copyAction.setEnabled(True) if QApplication.clipboard().text(): pasteAction.setEnabled(True) menu.exec_(self.mapToGlobal(e.pos()))
def __signal_pbCopyKml_clicked(self, cheked): # Extent Openlayers action = "map.getExtent().toGeometry().toString();" wkt = self.webViewMap.page().mainFrame().evaluateJavaScript(action) rect = QgsGeometry.fromWkt(wkt).boundingBox() srsGE = QgsCoordinateReferenceSystem( 4326, QgsCoordinateReferenceSystem.EpsgCrsId) coodTrans = QgsCoordinateTransform(self.__srsOL, srsGE, QgsProject.instance()) rect = coodTrans.transform( rect, QgsCoordinateTransform.ForwardTransform) line = QgsGeometry.fromRect(rect).asPolygon()[0] wkt = str(QgsGeometry.fromPolylineXY(line).asWkt()) # Kml proj4 = str(srsGE.toProj4()) kmlLine = bindogr.exportKml(wkt, proj4) kml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>"\ "<kml xmlns=\"http://www.opengis.net/kml/2.2\" " \ "xmlns:gx=\"http://www.google.com/kml/ext/2.2\" " \ "xmlns:kml=\"http://www.opengis.net/kml/2.2\" " \ "xmlns:atom=\"http://www.w3.org/2005/Atom\">" \ "<Placemark>" \ "<name>KML from Plugin Openlayers Overview for QGIS</name>" \ "<description>Extent of openlayers map from Plugin Openlayers \ Overview for QGIS</description>"\ "%s" \ "</Placemark></kml>" % kmlLine clipBoard = QApplication.clipboard() clipBoard.setText(kml)
def canvasReleaseEvent(self, event): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard. pt is QgsPointXY''' pt = self.snappoint(event.originalPixelPoint()) self.removeVertexMarker() if settings.showLocation: if self.marker is None: self.marker = QgsVertexMarker(self.canvas) self.marker.setIconSize(18) self.marker.setPenWidth(2) self.marker.setIconType(QgsVertexMarker.ICON_CROSS) self.marker.setCenter(pt) else: self.removeMarker() try: msg = self.formatCoord(pt) if msg is not None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage( "", "MGRS coordinate {} copied to the clipboard".format(msg), level=Qgis.Info, duration=4) except Exception as e: self.iface.messageBar().pushMessage( "", "Invalid coordinate: {}".format(e), level=Qgis.Warning, duration=4)
def doCopyLine(self): output = '' items = self.rasterInfoList.selectedItems() for r in items: output += r.text() + "\n" if output: clipboard = QApplication.clipboard() clipboard.setText(output)
def copySelected(self) -> None: """ Copy selected data to clipboard. """ text, success = self.download(allData=False, formatText=True) if success: clip_board = QApplication.clipboard() clip_board.setText(text)
def copy(self) -> None: """ Copy all data to clipboard. """ text, success = self.download(formatText=True) if success: clip_board = QApplication.clipboard() clip_board.setText(text)
def __init__(self, iface, setupObject): QDialog.__init__(self) self.iface = iface self.setupUi(self) self.clip = QApplication.clipboard() selectedPUIDDict = returnSelectedPUIDDict(setupObject) selectedPUDetailsDict = returnSelectedPUDetailsDict( setupObject, selectedPUIDDict) self.showSelectedIdentifyData(setupObject, selectedPUDetailsDict)
def onCopyXPath(self): def get_xpath(item): s = "" if item.parent(): s = get_xpath(item.parent()) t = item.text(0) if ":" in t: tt = t.split(":")[1] else: tt = t if t[0] == "@": tt = "@" + tt if s == "": return tt return s + "/" + tt xpath = get_xpath(self.currentItem()) QApplication.clipboard().setText(xpath)
def canvasReleaseEvent(self, event): """Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard. pt is QgsPointXY""" pt = self.snappoint(event.originalPixelPoint()) self.removeVertexMarker() # if we enable this we will get some vertex markers: # if self.marker is None: # self.marker = QgsVertexMarker(self.canvas) # self.marker.setIconSize(18) # self.marker.setPenWidth(2) # self.marker.setIconType(QgsVertexMarker.ICON_CROSS) # self.marker.setCenter(pt) if self.geodetic_use == 0: # use cartesian line_length = self.measureLine(self.linelayer, pt, False) whole_line_length = self.measureWholeLine(self.linelayer, False) dist_off_Line = self.closestPt( self.linelayer, pt, True, False)[1] #second False means we use Cartesian distance elif self.geodetic_use == 2: # use geodetic line_length = self.measureLine(self.linelayer, pt, True) whole_line_length = self.measureWholeLine(self.linelayer, True) dist_off_Line = self.closestPt(self.linelayer, pt, True, True)[1] if self.reversekp_status == 0: LL_message = '{:.{prec}f}'.format( line_length + self.offset, prec=self.kpdec) #round to specified decimal elif self.reversekp_status == 2: LL_message = '{:.{prec}f}'.format( whole_line_length - line_length + self.offset, prec=self.kpdec) #round to specified decimal DT_message = '{:.{prec}f}'.format( dist_off_Line, prec=self.dccdec) #round to specified decimal # check for output format below: if self.out_format == KpFindDialogInteractive.KP_out: # KP msg = 'KP ' + str(LL_message) elif self.out_format == KpFindDialogInteractive.KP_DCC_Out: # KP and DCC msg = 'KP ' + str(LL_message) + ' , DOL : ' + str( DT_message) + ' m' elif self.out_format == KpFindDialogInteractive.DMS_out: # Lat Lon and KP msg = self.formatCoord(pt)[0] + ', ' + self.formatCoord( pt)[1] + ' (KP ' + str(LL_message) + ')' if msg is not None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage(msg + ' on layer ' + str(self.linelayer.name()) + ' copied to clipboard', level=Qgis.Info, duration=2) else: self.iface.messageBar().pushMessage( 'Something went wrong with the coordinate composition', level=Qgis.Info, duration=2)
def keyPressEvent(self, e): if (e.modifiers() == Qt.ControlModifier or e.modifiers() == Qt.MetaModifier) and e.key() == Qt.Key_C: items = '' for r in range(self.rasterInfoList.count()): items.append(self.rasterInfoList.item(r).text() + "\n") if items: clipboard = QApplication.clipboard() clipboard.setText(items) else: QWidget.keyPressEvent(self, e)
def copyToClipboard(self): buffer = "" # intestazione for col in range(0, self.tableWidget.columnCount(), 1): if col > 0: buffer += '\t' # aggiungo un TAB buffer += self.tableWidget.horizontalHeaderItem(col).text() buffer += '\n' # vado a capo # valori delle righe for row in range(0, self.tableWidget.rowCount(), 1): for col in range(0, self.tableWidget.columnCount(), 1): if col > 0: buffer += '\t' # aggiungo un TAB buffer += self.tableWidget.item(row, col).text() buffer += '\n' # vado a capo QApplication.clipboard().setText(buffer)
def copy_text(self, text: str): """ Copies a text string to clipboard """ m = QMimeData() m.setText(text) cb = QApplication.clipboard() if sys.platform in ("linux", "linux2"): cb.setMimeData(m, QClipboard.Selection) cb.setMimeData(m, QClipboard.Clipboard)
def copyButton_clicked(self): cb = QApplication.clipboard() cb.clear(mode=cb.Clipboard) cb.setText("(%s, %s)" % (self.dockwidget.coordsEdit.text(), self.dockwidget.heightEdit.text()), mode=cb.Clipboard) self.iface.messageBar().pushMessage( "Sukces:", 'Skopiowano współrzedne x,y,h do schowka', level=Qgis.Success, duration=3)
def copyClipboard(self): if self.values is None: return else: clipboard = QApplication.clipboard() if self.uNoHeader.isChecked(): clipboard.setText('\n'.join( '%s\t%s' % x for x in zip(self.values[0], self.values[1]))) else: clipboard.setText('distance\televation\tpointID\n' + '\n'.join( '%s\t%s\t%s' % x for x in zip( self.values[0], self.values[1], self.values[2])))
def canvasReleaseEvent(self, e): pt = self.toMapCoordinates(e.pos()) mgrsCoord = self.toMgrs(pt) if mgrsCoord: clipboard = QApplication.clipboard() clipboard.setText(mgrsCoord) iface.messageBar().pushMessage( self.tr('MGRS Tools'), self.tr( 'Coordinate "{}" copied to clipboard'.format(mgrsCoord)), level=QgsMessageBar.INFO, duration=3)
def __init__(self, iface, setupObject): QDialog.__init__(self) self.iface = iface self.setupUi(self) self.clip = QApplication.clipboard() targetDict = makeTargetDict(setupObject) targetDialogRowList, numericColsList = makeTargetDialogRowList(setupObject) if targetDict != 'blank': setupObject.targetDict = targetDict setupObject.targetDialogRowList = targetDialogRowList setupObject.numericColsList = numericColsList self.loadTargetDictData(setupObject)
def paste_from_clipboard(self): text = QApplication.clipboard().text() sep = self.__get_separators() try: self.model = CbDataModel( text, separators=sep, decimal_point=',' if self.cb_decimalSep.isChecked() else '.', header_at_first=self.cb_firstRecord.isChecked()) except Exception as e: self.warning(str(e)) self.tableView.setModel(self.model) self.updateControls()
def keyPressEvent(self, e): if (e.modifiers() == Qt.ControlModifier or e.modifiers() == Qt.MetaModifier) and e.key() == Qt.Key_C: items = '' for rec in range(self.valueTable.rowCount()): items += '"' + self.valueTable.item( rec, 0).text() + '",' + self.valueTable.item( rec, 1).text() + "\n" if not items == '': clipboard = QApplication.clipboard() clipboard.setText(items) else: QWidget.keyPressEvent(self, e)
def mousePressEvent(self, e): """ Re-implemented to handle the mouse press event. e: the mouse press event (QMouseEvent) """ self.setFocus() if e.button() == Qt.MidButton: stringSel = QApplication.clipboard().text(QClipboard.Selection) if not self.is_cursor_on_last_line(): self.move_cursor_to_end() self.insertFromDropPaste(stringSel) e.accept() else: QsciScintilla.mousePressEvent(self, e)
def paste(self): """ Method to display data from the clipboard. XXX: It should reimplement the virtual QScintilla.paste method, but it seems not used by QScintilla code. """ stringPaste = QApplication.clipboard().text() if self.is_cursor_on_last_line(): if self.hasSelectedText(): self.removeSelectedText() else: self.move_cursor_to_end() self.insertFromDropPaste(stringPaste)
def canvasReleaseEvent(self, event): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard. pt is QgsPointXY''' pt = event.mapPoint() tz_name, msg = self.formatMessage(pt) if msg: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage( "", "'{}' copied to the clipboard".format(msg), level=Qgis.Info, duration=2)
def export(self): allTests = defaultdict(list) for test in tests.tests: allTests[test.group].append(test) s = "" for group, groupTests in allTests.items(): s += "- %s\n" % group for t in groupTests: s += "\t- %s\n" % t.name cb = QApplication.clipboard() cb.clear(mode=cb.Clipboard ) cb.setText(s, mode=cb.Clipboard) self.bar.pushMessage("", "Tests list has been copied to your clipboard", level=Qgis.Success, duration=5)
def testCopyPaste(self): p = QgsProject() l = QgsLayout(p) # clear clipboard mime_data = QMimeData() mime_data.setData("text/xml", QByteArray()) clipboard = QApplication.clipboard() clipboard.setMimeData(mime_data) # add an item item1 = QgsLayoutItemLabel(l) item1.setText('label 1') l.addLayoutItem(item1) item1.setSelected(True) item2 = QgsLayoutItemLabel(l) item2.setText('label 2') l.addLayoutItem(item2) item2.setSelected(True) view = QgsLayoutView() view.setCurrentLayout(l) self.assertFalse(view.hasItemsInClipboard()) view.copySelectedItems(QgsLayoutView.ClipboardCopy) self.assertTrue(view.hasItemsInClipboard()) pasted = view.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 2) self.assertIn(pasted[0], l.items()) self.assertIn(pasted[1], l.items()) self.assertIn( sip.cast(pasted[0], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) self.assertIn( sip.cast(pasted[1], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) # copy specific item view.copyItems([item2], QgsLayoutView.ClipboardCopy) l2 = QgsLayout(p) view2 = QgsLayoutView() view2.setCurrentLayout(l2) pasted = view2.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 1) self.assertIn(pasted[0], l2.items()) self.assertEqual( sip.cast(pasted[0], QgsLayoutItemLabel).text(), 'label 2')
def copyTable(self): #Writing the table to clipboard in excel form nr = int( self.sender().objectName() ) self.clipboard = QApplication.clipboard() text = "band" rowNames = list(self.profiles[nr].keys()) rowNames.remove("layer") rowNames.remove("l") for name in rowNames: text += "\t"+name text += "\n" for i in range( len(self.profiles[nr]["l"]) ): text += str(self.profiles[nr]["l"][i]) for j in range(len(rowNames)): text += "\t" + str(self.profiles[nr][rowNames[j]][i]) text += "\n" self.clipboard.setText(text)
def copyCanvas(self): extent = self.iface.mapCanvas().extent() canvas_crs = self.canvas.mapSettings().destinationCrs() if settings.bBoxCrs == 0: dst_crs = epsg4326 else: dst_crs = canvas_crs outStr = getExtentString(extent, canvas_crs, dst_crs) clipboard = QApplication.clipboard() clipboard.setText(outStr) self.iface.messageBar().pushMessage( "", "'{}' copied to the clipboard".format(outStr), level=Qgis.Info, duration=4)
def __init__(self, iface, setupObject, point): QDialog.__init__(self) self.iface = iface self.setupUi(self) self.clip = QApplication.clipboard() selectedPUIDList = returnPointPUIDList(setupObject, point) identDict, targetMetDict = makeIdentifyData(setupObject, selectedPUIDList) titleString = setIdentifyDialogWindowTitle(selectedPUIDList, identDict) if len(identDict.keys()) > 0: self.identDict = identDict self.targetMetDict = targetMetDict self.showIdentifyData(setupObject) self.setWindowTitle(titleString) self.setWindowTitle(titleString)
def zoomnow(self): clipboard = QApplication.clipboard() if not clipboard.mimeData().hasText(): return False text = unicode(clipboard.text()) # create and show the zoomtopaste dialog if text != "" and text.find(',') > 0: ret = text.split(",") xValue = float(ret[1]) yValue = float(ret[0]) if xValue > 0 and yValue > 0: if self.first_start == True: self.first_start = False self.dlg = zoomtopasteDialog() self.dlg.xCoord.setText(str(xValue)) self.dlg.yCoord.setText(str(yValue)) scale = self.dlg.spinBoxScale.value() # Create a rectangle to cover the new extent rect = QgsRectangle((xValue) - scale, (yValue) - scale, (xValue) + scale, (yValue) + scale) # Get the map canvas mc = self.iface.mapCanvas() # Set the extent to our new rectangle mc.setExtent(rect) # Refresh the map mc.refresh() settings = QSettings("MicroResources", "zoomtopaste") settings.setValue("coordinate/x", str(xValue)) settings.setValue("coordinate/y", str(yValue)) else: self.iface.messageBar().pushMessage( "Error zoomNow", "Im Clipbord sind keine oder falsche Daten: " + text, level=Qgis.Warning, duration=3)
def clicked(self, pt, b): '''Capture the coordinate when the mouse button has been released, format it, and copy it to the clipboard.''' try: if self.capture4326: canvasCRS = self.canvas.mapSettings().destinationCrs() transform = QgsCoordinateTransform(canvasCRS, epsg4326, QgsProject.instance()) pt4326 = transform.transform(pt.x(), pt.y()) self.capturesig.emit(pt4326) return msg = self.formatCoord(pt, self.settings.delimiter) formatString = self.coordFormatString() if msg != None: clipboard = QApplication.clipboard() clipboard.setText(msg) self.iface.messageBar().pushMessage("", "{} coordinate {} copied to the clipboard".format(formatString, msg), level=Qgis.Info, duration=4) except Exception as e: self.iface.messageBar().pushMessage("", "Invalid coordinate: {}".format(e), level=Qgis.Warning, duration=4)
def export(self): allTests = defaultdict(list) for test in tests.tests: allTests[test.group].append(test) s = "" for group, groupTests in iteritems(allTests.iteritems): s += "- %s\n" % group for t in groupTests: s += "\t- %s\n" % t.name cb = QApplication.clipboard() cb.clear(mode=cb.Clipboard) cb.setText(s, mode=cb.Clipboard) self.bar.pushMessage("", "Tests list has been copied to your clipboard", level=QgsMessageBar.SUCCESS, duration=5)
def getExtent(self, bbox): if bbox.isNull(): return canvasCRS = self.canvas.mapSettings().destinationCrs() if settings.bBoxCrs == 0: dstCRS = epsg4326 else: dstCRS = canvasCRS outStr = getExtentString(bbox, canvasCRS, dstCRS) clipboard = QApplication.clipboard() clipboard.setText(outStr) self.iface.messageBar().pushMessage( "", "'{}' copied to the clipboard".format(outStr), level=Qgis.Info, duration=4)
def canvasReleaseEvent(self, e): pt = self.toMapCoordinates(e.pos()) w3wCoord = self.toW3W(pt) if w3wCoord: iface.messageBar().pushMessage( "what3words", "The 3 word address: '{}' has been copied to the clipboard". format(w3wCoord), level=Qgis.Info, duration=6) clipboard = QApplication.clipboard() clipboard.setText(w3wCoord) else: iface.messageBar().pushMessage( "what3words", "Could not convert the selected point to a 3 word address", level=Qgis.Warning, duration=3)
def testCopyPaste(self): p = QgsProject() l = QgsLayout(p) # clear clipboard mime_data = QMimeData() mime_data.setData("text/xml", QByteArray()) clipboard = QApplication.clipboard() clipboard.setMimeData(mime_data) # add an item item1 = QgsLayoutItemLabel(l) item1.setText('label 1') l.addLayoutItem(item1) item1.setSelected(True) item2 = QgsLayoutItemLabel(l) item2.setText('label 2') l.addLayoutItem(item2) item2.setSelected(True) view = QgsLayoutView() view.setCurrentLayout(l) self.assertFalse(view.hasItemsInClipboard()) view.copySelectedItems(QgsLayoutView.ClipboardCopy) self.assertTrue(view.hasItemsInClipboard()) pasted = view.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 2) self.assertIn(pasted[0], l.items()) self.assertIn(pasted[1], l.items()) self.assertIn(sip.cast(pasted[0], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) self.assertIn(sip.cast(pasted[1], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) # copy specific item view.copyItems([item2], QgsLayoutView.ClipboardCopy) l2 = QgsLayout(p) view2 = QgsLayoutView() view2.setCurrentLayout(l2) pasted = view2.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 1) self.assertIn(pasted[0], l2.items()) self.assertEqual(sip.cast(pasted[0], QgsLayoutItemLabel).text(), 'label 2')
def copyCanvas(self): extent = self.iface.mapCanvas().extent() canvasCrs = self.canvas.mapSettings().destinationCrs() if settings.bBoxCrs == 0 and canvasCrs != epsg4326: transform = QgsCoordinateTransform(canvasCrs, epsg4326, QgsProject.instance()) p1x, p1y = transform.transform(float(extent.xMinimum()), float(extent.yMinimum())) p2x, p2y = transform.transform(float(extent.xMaximum()), float(extent.yMaximum())) extent.set(p1x, p1y, p2x, p2y) delim = settings.bBoxDelimiter prefix = settings.bBoxPrefix suffix = settings.bBoxSuffix precision = settings.bBoxDigits outStr = '' minX = extent.xMinimum() minY = extent.yMinimum() maxX = extent.xMaximum() maxY = extent.yMaximum() if settings.bBoxFormat == 0: # minX,minY,maxX,maxY - using the delimiter outStr = '{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}'.format( minX, delim, minY, delim, maxX, delim, maxY, prec=precision) elif settings.bBoxFormat == 1: # minX,maxX,minY,maxY - Using the selected delimiter' outStr = '{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}{}{:.{prec}f}'.format( minX, delim, maxX, delim, minY, delim, maxY, prec=precision) elif settings.bBoxFormat == 2: # x1 y1,x2 y2,x3 y3,x4 y4,x1 y1 - Polygon format outStr = '{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f}'.format( minX, minY, minX, maxY, maxX, maxY, maxX, minY, minX, minY, prec=precision) elif settings.bBoxFormat == 3: # x1,y1 x2,y2 x3,y3 x4,y4 x1,y1 - Polygon format outStr = '{:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f} {:.{prec}f},{:.{prec}f}'.format( minX, minY, minX, maxY, maxX, maxY, maxX, minY, minX, minY, prec=precision) elif settings.bBoxFormat == 4: # WKT Polygon outStr = extent.asWktPolygon() elif settings.bBoxFormat == 5: # bbox: [minX, minY, maxX, maxY] - MapProxy outStr = 'bbox: [{}, {}, {}, {}]'.format( minX, minY, maxX, maxY) elif settings.bBoxFormat == 6: # bbox: [minX, minY, maxX, maxY] - MapProxy outStr = 'bbox={},{},{},{}'.format( minX, minY, maxX, maxY) outStr = '{}{}{}'.format(prefix, outStr, suffix) clipboard = QApplication.clipboard() clipboard.setText(outStr) self.iface.messageBar().pushMessage("", "'{}' copied to the clipboard".format(outStr), level=Qgis.Info, duration=4)
def keyPressEvent(self, event): if event.modifiers() in [Qt.ControlModifier, Qt.MetaModifier] and event.key() == Qt.Key_C: clipboard = QApplication.clipboard() clipboard.setText("\n".join(self.calculator.data)) else: QDialog.keyPressEvent(self, event)
def copyUrl(self): QApplication.clipboard().setText(self.repo.url)
def testCopyPaste(self): p = QgsProject() l = QgsLayout(p) # clear clipboard mime_data = QMimeData() mime_data.setData("text/xml", QByteArray()) clipboard = QApplication.clipboard() clipboard.setMimeData(mime_data) # add an item item1 = QgsLayoutItemLabel(l) item1.setText('label 1') l.addLayoutItem(item1) item1.setSelected(True) item2 = QgsLayoutItemLabel(l) item2.setText('label 2') l.addLayoutItem(item2) item2.setSelected(True) # multiframes multiframe1 = QgsLayoutItemHtml(l) multiframe1.setHtml('mf1') l.addMultiFrame(multiframe1) frame1 = QgsLayoutFrame(l, multiframe1) frame1.setId('frame1a') multiframe1.addFrame(frame1) frame1b = QgsLayoutFrame(l, multiframe1) frame1b.setId('frame1b') multiframe1.addFrame(frame1b) # not selected frame1c = QgsLayoutFrame(l, multiframe1) frame1c.setId('frame1b') multiframe1.addFrame(frame1c) # not selected multiframe2 = QgsLayoutItemHtml(l) multiframe2.setHtml('mf2') l.addMultiFrame(multiframe2) frame2 = QgsLayoutFrame(l, multiframe2) frame2.setId('frame2') multiframe2.addFrame(frame2) frame1.setSelected(True) frame2.setSelected(True) view = QgsLayoutView() view.setCurrentLayout(l) self.assertFalse(view.hasItemsInClipboard()) view.copySelectedItems(QgsLayoutView.ClipboardCopy) self.assertTrue(view.hasItemsInClipboard()) pasted = view.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 4) new_multiframes = [m for m in l.multiFrames() if m not in [multiframe1, multiframe2]] self.assertEqual(len(new_multiframes), 2) self.assertIn(pasted[0], l.items()) self.assertIn(pasted[1], l.items()) labels = [p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutLabel] self.assertIn(sip.cast(labels[0], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) self.assertIn(sip.cast(labels[1], QgsLayoutItemLabel).text(), ('label 1', 'label 2')) frames = [p for p in pasted if p.type() == QgsLayoutItemRegistry.LayoutFrame] pasted_frame1 = sip.cast(frames[0], QgsLayoutFrame) pasted_frame2 = sip.cast(frames[1], QgsLayoutFrame) self.assertIn(pasted_frame1.multiFrame(), new_multiframes) self.assertIn(new_multiframes[0].frames()[0].uuid(), (pasted_frame1.uuid(), pasted_frame2.uuid())) self.assertIn(pasted_frame2.multiFrame(), new_multiframes) self.assertIn(new_multiframes[1].frames()[0].uuid(), (pasted_frame1.uuid(), pasted_frame2.uuid())) self.assertEqual(frame1.multiFrame(), multiframe1) self.assertCountEqual(multiframe1.frames(), [frame1, frame1b, frame1c]) self.assertEqual(frame1b.multiFrame(), multiframe1) self.assertEqual(frame1c.multiFrame(), multiframe1) self.assertEqual(frame2.multiFrame(), multiframe2) self.assertCountEqual(multiframe2.frames(), [frame2]) # copy specific item view.copyItems([item2], QgsLayoutView.ClipboardCopy) l2 = QgsLayout(p) view2 = QgsLayoutView() view2.setCurrentLayout(l2) pasted = view2.pasteItems(QgsLayoutView.PasteModeCursor) self.assertEqual(len(pasted), 1) self.assertIn(pasted[0], l2.items()) self.assertEqual(sip.cast(pasted[0], QgsLayoutItemLabel).text(), 'label 2')