def _loadLayer(self): fullLayerPath = os.path.join(self._projectPath, self._settings.path) filePath = QFileInfo(fullLayerPath) layer = None if filePath.exists(): layer = layers.loadShapefileLayer(fullLayerPath, self._settings.name) else: wkbType = layers.geometryToWkbType(self._settings.geometry, self._settings.multi) if not filePath.dir().exists(): os.makedirs(filePath.dir().absolutePath()) layer = layers.createShapefile(fullLayerPath, self._settings.name, wkbType, self._settings.crs, self.fields) if layer and layer.isValid(): layer = layers.addLayerToLegend(self._iface, layer) self._setDefaultSnapping(layer) layer.loadNamedStyle(self._settings.stylePath) self.name = self._settings.name self.layer = layer self.layerId = layer.id() else: self.layer = None self.layerId = ''
def _loadLogLayer(self): fullLayerPath = os.path.join(self._projectPath, self._settings.logPath) filePath = QFileInfo(fullLayerPath) layer = None if filePath.exists(): layer = layers.loadShapefileLayer(fullLayerPath, self._settings.logName) else: if not filePath.dir().exists(): os.makedirs(filePath.dir().absolutePath()) fields = QgsFields() fields.append(QgsField('timestamp', QVariant.String, '', 10, 0, 'timestamp')) fields.append(QgsField('event', QVariant.String, '', 6, 0, 'event')) fields.extend(self.fields) layer = layers.createShapefile(fullLayerPath, self._settings.logName, self.layer.wkbType(), self._settings.crs, fields) if layer and layer.isValid(): layer.editFormConfig().setSuppress(QgsEditFormConfig.SuppressOn) self.logLayer = layer self.logLayerId = layer.id() else: self.logLayer = None self.logLayerId = ''
def downloadFile(self, url_to_download, fout): " get the file from remote url to local folder " url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) fileName = path.join(fout, str(fileInfo.fileName())) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information( self, "ERROR", "Cant save the file %s: %s." % (fileName, self.outFile.errorString()) ) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False tpath = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if tpath: tpath = str(tpath) else: tpath = sep # Download the file. print(" INFO: Blender Download Started ! ") self.httpGetId = self.http.get(tpath, self.outFile)
def __init__(self, methodName): """Run once on class initialisation.""" unittest.TestCase.__init__(self, methodName) myPath = os.path.join(TEST_DATA_DIR, 'landsat.tif') rasterFileInfo = QFileInfo(myPath) mRasterLayer = QgsRasterLayer(rasterFileInfo.filePath(), rasterFileInfo.completeBaseName()) rasterRenderer = QgsMultiBandColorRenderer( mRasterLayer.dataProvider(), 2, 3, 4) mRasterLayer.setRenderer(rasterRenderer) #pipe = mRasterLayer.pipe() #assert pipe.set(rasterRenderer), 'Cannot set pipe renderer' QgsMapLayerRegistry.instance().addMapLayers([mRasterLayer]) # create composition with composer map self.mMapRenderer = QgsMapRenderer() layerStringList = QStringList() layerStringList.append(mRasterLayer.id()) self.mMapRenderer.setLayerSet(layerStringList) self.mMapRenderer.setProjectionsEnabled(False) self.mComposition = QgsComposition(self.mMapRenderer) self.mComposition.setPaperSize(297, 210) self.mComposerMap = QgsComposerMap(self.mComposition, 20, 20, 200, 100) self.mComposerMap.setFrameEnabled(True) self.mComposition.addComposerMap(self.mComposerMap)
def testIdentify(self): myPath = os.path.join(unitTestDataPath(), 'landsat.tif') myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage myPoint = QgsPoint(786690, 3345803) #print 'Extents: %s' % myRasterLayer.extent().toString() #myResult, myRasterValues = myRasterLayer.identify(myPoint) #assert myResult myRasterValues = myRasterLayer.dataProvider().identify(myPoint, QgsRasterDataProvider.IdentifyFormatValue ) assert len( myRasterValues ) > 0 # Get the name of the first band myBand = myRasterValues.keys()[0] #myExpectedName = QString('Band 1') myExpectedBand = 1 myMessage = 'Expected "%s" got "%s" for first raster band name' % ( myExpectedBand, myBand) assert myExpectedBand == myBand, myMessage # Convert each band value to a list of ints then to a string myValues = myRasterValues.values() myIntValues = [] for myValue in myValues: #myIntValues.append(int(str(myValue))) myIntValues.append( myValue.toInt()[0] ) myValues = str(myIntValues) myExpectedValues = '[127, 141, 112, 72, 86, 126, 156, 211, 170]' myMessage = 'Expected: %s\nGot: %s' % (myValues, myExpectedValues) self.assertEquals(myValues, myExpectedValues, myMessage)
def accept(self): input_path = str(self.leInputPath.text()) output_path = str(self.leOutputPath.text()) if not output_path.endswith('.tif'): QMessageBox.warning( self.parent, self.tr('InaSAFE'), (self.tr('Output file name must be tif file'))) if not os.path.exists(input_path): QMessageBox.warning( self.parent, self.tr('InaSAFE'), (self.tr('Input file is not exist'))) return my_algorithm = str(self.cboAlgorithm.currentText()).lower() fileName = convert_mmi_data(input_path, output_path, the_algorithm=my_algorithm, algorithm_name=False) if self.cBLoadLayer.isChecked(): fileInfo = QFileInfo(fileName) baseName = fileInfo.baseName() my_raster_layer = QgsRasterLayer(fileName, baseName) if not my_raster_layer.isValid(): LOGGER.debug("Failed to load") else: QgsMapLayerRegistry.instance().addMapLayer(my_raster_layer) self.done(self.Accepted) if not self.test_mode: QMessageBox.warning( self.parent, self.tr('InaSAFE'), (self.tr('Success to convert %1 to %2'). arg(input_path).arg(output_path)))
def export(self): if self.__path is not None: default_export_path = self.__path else: default_export_path = PlotSettingsModel().getDefaultPlotPath() dialog = QFileDialog(self.__active_plot_panel) dialog.setFileMode(QFileDialog.AnyFile) # dialog.setNameFilter("Image (*.png);; PDF (*.pdf)") dialog.setNameFilter("Image (*.png)") dialog.setWindowTitle("Export plot") dialog.setDirectory(default_export_path) dialog.setOption(QFileDialog.DontUseNativeDialog, True) dialog.setLabelText(QFileDialog.FileType, "Select file type: ") dialog.setAcceptMode(QFileDialog.AcceptSave) dialog.selectFile(self.getDefaultFileName()) if dialog.exec_(): result = dialog.selectedFiles() assert isinstance(result, QStringList) if len(result) == 1: file_info = QFileInfo(result[0]) self.__file_name = file_info.fileName() self.__path = file_info.path() self.__selected_file_type = dialog.selectedNameFilter() name = self.__active_plot_panel.getName() url = self.__active_plot_panel.getUrl() web_page = PlotWebPage("export - %s" % name) web_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) web_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) web_page.setViewportSize(QSize(self.__width, self.__height)) self.__bridge = PlotBridge(web_page, url) self.__bridge.plotReady.connect(self.plotReady) QApplication.setOverrideCursor(QCursor(Qt.WaitCursor))
def split_bands(pathIn,pathOut): # Recibe un path de entrada (raster multibanda) y devuelve las bandas por separado fileInfo=QFileInfo(pathIn) baseName=fileInfo.baseName() layer=QgsRasterLayer(pathIn, baseName) if not layer.isValid(): print "Error importing Micasense Mosaic to split" print "Splitting bands from " + baseName numBands=layer.bandCount() i=1 entries=[] output=[] while(i<=numBands): band = QgsRasterCalculatorEntry() band.ref = "band@"+str(i) band.raster=layer band.bandNumber=i entries.append(band) # Saves the current band as a separate file calc=QgsRasterCalculator(band.ref, pathOut+ "/" +baseName+"_band_"+str(i)+".tif","GTiff",layer.extent(),layer.width(),layer.height(), entries) calc.processCalculation() output.append(pathOut+"/"+baseName+"_band_"+str(i)+".tif") i=i+1 return output
def loadSymbologyFile(self): """ Load a QML file to set the layer style """ settings = QSettings() ultimaRutaQml = settings.value( 'Paths/qml', QVariant('.') ).toString() symPath = QFileDialog.getOpenFileName(self, "Open a style file (.qml)", ultimaRutaQml, "QGIS Layer Style File (*.qml)") if isfile(symPath): layer = self.currentItem().canvasLayer.layer() res = layer.loadNamedStyle(symPath) if res[1]: self.refreshLayerSymbology(self.currentItem().canvasLayer.layer()) self.showMessage(self, 'Load style', 'New style has been applied to the layer ' + self.currentItem().text(0) + '.', QMessageBox.Information ) # Immediately refresh layer if hasattr(layer, "setCacheImage"): layer.setCacheImage(None) layer.triggerRepaint() else: self.showMessage( self, 'Load style', 'Error loading style file. Please check if match the layer ' + self.currentItem().text(0) + '.', QMessageBox.Warning ) symInfo = QFileInfo(symPath) settings.setValue('Paths/qml', QVariant( symInfo.absolutePath()))
def _add_tabular_layer(self, tabular_layer, layer_name): """Add a tabular layer to the folder. :param tabular_layer: The layer to add. :type tabular_layer: QgsVectorLayer :param layer_name: The name of the layer in the datastore. :type layer_name: str :returns: A two-tuple. The first element will be True if we could add the layer to the datastore. The second element will be the layer name which has been used or the error message. :rtype: (bool, str) .. versionadded:: 4.0 """ output = QFileInfo( self.uri.filePath(layer_name + '.csv')) QgsVectorFileWriter.writeAsVectorFormat( tabular_layer, output.absoluteFilePath(), 'utf-8', None, 'CSV') assert output.exists() return True, output.baseName()
def downloadFile(self): url = QUrl(self.downloadUrl) fileInfo = QFileInfo(url.path()) #fileName = fileInfo.fileName() fileName = self.targetDirectory + fileInfo.fileName() if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False print url path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Right at the end we append the query string that is lost, the original author did not include this unfortunately. parsedUrl = urlparse(self.downloadUrl) if not parsedUrl.query == '': # fix this mess, otherwise leave it alone path = path + "?" + parsedUrl.query print path # Download the file. self.httpGetId = self.http.get(path, self.outFile)
def run_clicked(self): start = clock() self.setEnabled(False) input = self.layerPath if unicode(self.output.text()) == '': try: output = os.environ['temp']+'out'+unicode(int(clock()*10000))+'.tif' except: if os.access('/tmp/kuw_filter', os.F_OK)==False: os.mkdir('/tmp/kuw_filter') output = '/tmp/kuw_filter/out'+unicode(int(clock()*10000))+'.tif' else: output = unicode(self.output.text()) refb = int(self.refb.text()) memuse = int(self.mem.text()) self.setCursor(QCursor(Qt.WaitCursor)) if dofilter(self, input, output, refb, memuse) : self.msgbox(QApplication.translate('kuw_filterdialog','Time elapsed:\n ', None, QApplication.UnicodeUTF8)+unicode(int((clock()-start)/3600))+'h'+unicode(int((clock()-start)/60))+'m'+unicode((0.5+clock()-start)%60)[0:5]+'s') if self.addout.isChecked(): fileName = unicode(output) fileInfo = QFileInfo(fileName) baseName = fileInfo.baseName() iface.addRasterLayer(fileName, baseName) self.setCursor(QCursor(Qt.ArrowCursor)) self.setEnabled(True) self.close()
def testIdentify(self): myPath = os.path.abspath(os.path.join(__file__, '..', '..', '..', 'testdata', 'landsat.tif')) myFileInfo = QFileInfo(myPath) myBaseName = myFileInfo.baseName() myRasterLayer = QgsRasterLayer(myPath, myBaseName) myMessage = 'Raster not loaded: %s' % myPath assert myRasterLayer.isValid(), myMessage myPoint = QgsPoint(786690, 3345803) #print 'Extents: %s' % myRasterLayer.extent().toString() myResult, myRasterValues = myRasterLayer.identify(myPoint) assert myResult # Get the name of the first band myBandName = myRasterValues.keys()[0] myExpectedName = QString('Band 1') myMessage = 'Expected "%s" got "%s" for first raster band name' % ( myExpectedName, myBandName) assert myExpectedName == myBandName, myMessage # Convert each band value to a list of ints then to a string myValues = myRasterValues.values() myIntValues = [] for myValue in myValues: myIntValues.append(int(str(myValue))) myValues = str(myIntValues) myExpectedValues = '[127, 141, 112, 72, 86, 126, 156, 211, 170]' myMessage = 'Expected: %s\nGot: %s' % (myValues, myExpectedValues) self.assertEquals(myValues, myExpectedValues, myMessage)
def restoreDir(self): "用户点击了“默认运行目录”按钮。" path = self.txtPath.text().strip() fi = QFileInfo(path) if path == "" or not fi.exists(): return self.txtDir.setText(fi.dir().absolutePath())
def batchFinished( self ): self.base.stop() if len(self.errors) > 0: msg = u"Processing of the following files ended with error: <br><br>" + "<br><br>".join( self.errors ) QErrorMessage( self ).showMessage( msg ) inDir = self.getInputFileName() outDir = self.getOutputFileName() if outDir is None or inDir == outDir: self.outFiles = self.inFiles # load layers managing the render flag to avoid waste of time canvas = self.iface.mapCanvas() previousRenderFlag = canvas.renderFlag() canvas.setRenderFlag( False ) notCreatedList = [] for item in self.outFiles: fileInfo = QFileInfo( item ) if fileInfo.exists(): if self.base.loadCheckBox.isChecked(): self.addLayerIntoCanvas( fileInfo ) else: notCreatedList.append( item ) canvas.setRenderFlag( previousRenderFlag ) if len( notCreatedList ) == 0: QMessageBox.information( self, self.tr( "Finished" ), self.tr( "Operation completed." ) ) else: QMessageBox.warning( self, self.tr( "Warning" ), self.tr( "The following files were not created: \n{0}" ).format( ', '.join( notCreatedList ) ) )
def on_upload_document(self): ''' Slot raised when the user clicks to upload a supporting document. ''' document_str = QApplication.translate( "SupportingDocuments", "Specify the Document File Location" ) documents = self.select_file_dialog(document_str) cbo_index = self.doc_type_cbo.currentIndex() doc_id = self.doc_type_cbo.itemData(cbo_index) for doc in documents: self.supporting_doc_manager.insertDocumentFromFile( doc, doc_id, self.social_tenure, self.current_party_count ) # Set last path if len(documents) > 0: doc = documents[0] fi = QFileInfo(doc) dir_path = fi.absolutePath() set_last_document_path(dir_path) model_objs = self.supporting_doc_manager.model_objects() self.onUploadDocument.emit(model_objs)
def downloadFile(self, url_to_download, download_location): url = QUrl(url_to_download) fileInfo = QFileInfo(url.path()) #fileName = fileInfo.fileName() fileName = download_location + fileInfo.fileName() self.file_name = fileName print("Filename = " + fileName) if QFile.exists(fileName): QFile.remove(fileName) self.outFile = QFile(fileName) if not self.outFile.open(QIODevice.WriteOnly): QMessageBox.information(self, 'Error', 'Unable to save the file %s: %s.' % (fileName, self.outFile.errorString())) self.outFile = None return mode = QHttp.ConnectionModeHttp port = url.port() if port == -1: port = 0 self.http.setHost(url.host(), mode, port) self.httpRequestAborted = False path = QUrl.toPercentEncoding(url.path(), "!$&'()*+,;=:@/") if path: path = str(path) else: path = '/' # Download the file. self.httpGetId = self.http.get(path, self.outFile) return fileName
def accept(self): """ Handle OK button """ layer_title = self.input_title.text() netcdf_uri = 'NETCDF:"'+self.file_path+'":'+self.subdataset output_uri = self.file_dir + "/" + layer_title + ".tif" # check if default folder is used if not self.use_default_dir.isChecked(): self.file_dir = self.output_path.text() output_uri = self.file_dir #self.display_log.append("Result path " + output_uri) full_cmd = 'gdal_translate -b ' + self.band + ' -a_srs ' + self.input_authid +' -of GTiff ' + netcdf_uri + ' "' + output_uri +'"' subprocess.Popen(full_cmd, shell=True) # if not self.use_input_crs.isChecked(): # transformed_uri = self.file_dir + "/" + layer_title + "_transformed.tif" # transform_cmd = 'gdalwarp -overwrite -s_srs ' + self.input_authid + ' -t_srs '+ self.output_authid +' -of GTiff ' + output_uri + '' + transformed_uri +'' # subprocess.Popen(transform_cmd, shell=True) # output_uri = transformed_uri file_info = QFileInfo(output_uri) base_name = file_info.baseName() result_layer = QgsRasterLayer(output_uri, base_name) result_layer.isValid() if not result_layer.isValid(): QgsMessageLog.logMessage("Layer is invalid") msg_bar = self.iface.messageBar().createMessage("Warning", "Layer is not loaded automatically") self.uri = output_uri self.base_name = base_name button_load_result = QPushButton(msg_bar) button_load_result.setText("Load Result") button_load_result.pressed.connect(self.load_manually) msg_bar.layout().addWidget(button_load_result) self.iface.messageBar().pushWidget(msg_bar, QgsMessageBar.WARNING, duration=15) else: QgsMapLayerRegistry.instance().addMapLayer(result_layer)
def _export_composition_as_image(self, composition, file_path): """ Export the composition as a raster image. """ num_pages = composition.numPages() for p in range(num_pages): img = composition.printPageAsRaster(p) if img.isNull(): msg = QApplication.translate("DocumentGenerator", u"Memory allocation error. Please try " u"a lower resolution or a smaller paper size.") raise Exception(msg) if p == 0: state = img.save(file_path) else: fi = QFileInfo(file_path) file_path = u"{0}/{1}_{2}.{3}".format(fi.absolutePath(), fi.baseName(), (p+1), fi.suffix()) state = img.save(file_path) if not state: msg = QApplication.translate("DocumentGenerator", u"Error creating {0}.".format(file_path)) raise Exception(msg)
def exportXMLToFile(self): """ NO DOCUMENTATION """ assert self.has_selected_item() # Ask the users where they want to save the file start_dir = "" opus_home = os.environ.get("OPUS_HOME") if opus_home: start_dir_test = os.path.join(opus_home, "project_configs") if start_dir_test: start_dir = start_dir_test configDialog = QFileDialog() filter_str = QString("*.xml") fd = configDialog.getSaveFileName( self.manager.base_widget, QString("Save As..."), QString(start_dir), filter_str ) # Check for cancel if len(fd) == 0: return fileNameInfo = QFileInfo(QString(fd)) fileName = fileNameInfo.fileName().trimmed() fileNamePath = fileNameInfo.absolutePath().trimmed() saveName = os.path.join(str(fileNamePath), str(fileName)) # proper root node for XmlConfiguration root_node = Element("opus_project") import copy root_node.append(copy.deepcopy(self.selected_item().node)) # Write out the file ElementTree(root_node).write(saveName)
def itemAdd(self): fileNames = QFileDialog.getOpenFileNames(None, u"{0} -- {1}".format(qApp.applicationName(), Img2GifWidget.AppName), '.', u'所有文件(*.*);;BMP文件(*.bmp);;PNG文件(*.png);;JPG文件(*.jpg *.jpeg)') for fn in fileNames: f = QFileInfo(fn) if unicode(f.suffix().toLower()) in ['jpg', 'png', 'bmp', 'jpeg']: self.listWidget.addItem(fn)
def setLastUsedDir(filePath): settings = QSettings() fileInfo = QFileInfo(filePath) if fileInfo.isDir(): dirPath = fileInfo.filePath() else: dirPath = fileInfo.path() settings.setValue( "/GdalTools/lastUsedDir", dirPath )
def dropEvent(self, event): for file in event.mimeData().urls(): fi = QFileInfo(QFile(file.toLocalFile())) if fi.suffix() in self.acceptedFormats: self.addImageToTable(fi.filePath(), self.table.rowCount()) else: self.statusBar.showMessage('File format of {} not supported'.format(fi.fileName()), 5000) event.accept()
def __load_layer(self, path): fileName = path fileInfo = QFileInfo(fileName) baseName = fileInfo.baseName() rlayer = QgsRasterLayer(fileName, baseName) if not rlayer.isValid(): raise Exception("Computation finished, but layer failed to load. Inspect the path zou specified for the output layer.") return rlayer
def importSplus(self): dlg = splusimport.Dialog(self.iface) dlg.setModal(True) dlg.setWindowTitle('Import S-Plus map') if dlg.exec_() == QDialog.Accepted: file = QFileInfo(dlg.lineEdit_2.text()) nl = QgsVectorLayer(dlg.lineEdit_2.text(), unicode(file.baseName()), "ogr") QgsMapLayerRegistry.instance().addMapLayers([nl])
def open_raster(self): path = self.le_shapefile.text() file_info = QFileInfo(path) layer = QgsRasterLayer(path, file_info.baseName()) # noinspection PyArgumentList QgsMapLayerRegistry.instance().addMapLayer(layer) self.signalStatus.emit(3, tr('Successful import from %s' % path))
def lastModified(self, path): fi = QFileInfo(path) if fi.exists(): return fi.lastModified() else: err = 'No such file or directory' qDebug("FileSystem.lastModified - %s: '%s'" % (err, path)) return QDateTime()
def setFileIcon(self, path): "每当txtPath的值改变时,就设置快捷方式的图标" fi = QFileInfo(path) if not fi.exists(): self.shortcutIcon = QIcon(":/images/unknown.png") else: ip = QFileIconProvider() self.shortcutIcon = ip.icon(fi) self.btnFace.setIcon(self.shortcutIcon)
def __init__(self, mainwindow): self.mainwindow = mainwindow # create map canvas self.canvas = QgsMapCanvas(self.mainwindow.widgetMap) self.canvas.setCanvasColor(Qt.yellow) self.canvas.enableAntiAliasing(True) self.canvas.useQImageToRender(False) self.canvas.show() self.canvas.parentWin = mainwindow debugString = QString("Finished Loading Canvas...") self.mainwindow.statusbar.showMessage(debugString) # lay our widgets out in the main window self.layout = QVBoxLayout(self.mainwindow.widgetMap) self.layout.addWidget(self.canvas) # Link in the map tools QObject.connect(self.mainwindow.mpActionZoomIn, SIGNAL("triggered()"), self.zoomIn) QObject.connect(self.mainwindow.mpActionZoomOut, SIGNAL("triggered()"), self.zoomOut) QObject.connect(self.mainwindow.mpActionPan, SIGNAL("triggered()"), self.pan) # Map tools self.toolPan = QgsMapToolPan(self.canvas) self.toolPan.setAction(self.mainwindow.mpActionPan) self.toolZoomIn = QgsMapToolZoom(self.canvas, False) self.toolZoomIn.setAction(self.mainwindow.mpActionZoomIn) self.toolZoomOut = QgsMapToolZoom(self.canvas, True) self.toolZoomOut.setAction(self.mainwindow.mpActionZoomOut) ##### Lets test out a simple map self.layers = [] f = "data/st99_d00.shp" f_string = QString(f) info = QFileInfo(QString(f)) # create layer layer = QgsVectorLayer(QString(f), info.completeBaseName(), "ogr") if not layer.isValid(): # Deal with the error debugString = QString("Error Loading Layer...") self.mainwindow.statusbar.showMessage(debugString) return QgsMapLayerRegistry.instance().addMapLayer(layer) # set extent to the extent of our layer self.canvas.setExtent(layer.extent()) # Set the transparency for the layer #layer.setTransparency(190) # set the map canvas layer set cl = QgsMapCanvasLayer(layer) self.layers.insert(0,cl) self.canvas.setLayerSet(self.layers)
def selectedFile(self): """ Renvoi le fichier selectionné pour la sauvegarde""" # Récupération du fichier selectionné fichier = self.fileField.text() output = "%s%s%s" % (self.currentDir, os.sep, fichier) info = QFileInfo(output) # Si l'utilisateur n'a pas spécifié de suffix, on l'ajoute if info.suffix() != self.suffix[1:]: output = "%s%s" % (output, self.suffix) return output
def __init__(self, iface): self.iface = iface self.canvas = self.iface.mapCanvas() self.qgsVersion = unicode(QGis.QGIS_VERSION_INT) pluginPath = os.path.abspath(os.path.dirname(__file__)) overrideLocale = QSettings().value('locale/overrideFlag', False, bool) if not overrideLocale: locale = QLocale.system().name()[:2] else: locale = QSettings().value('locale/userLocale', '') translationPath = '{}/i18n/landmark_{}.qm'.format(pluginPath, locale) if QFileInfo(translationPath).exists(): self.translator = QTranslator() self.translator.load(translationPath) QCoreApplication.installTranslator(self.translator)
def addMediaFile(self): path = '.' filename = self.labeltool.getCurrentFilename() if (filename is not None) and (len(filename) > 0): path = QFileInfo(filename).path() image_types = [ '*.jpg', '*.bmp', '*.png', '*.pgm', '*.ppm', '*.tiff', '*.tif', '*.gif' ] video_types = ['*.mp4', '*.mpg', '*.mpeg', '*.avi', '*.mov', '*.vob'] format_str = ' '.join(image_types + video_types) fnames = QFileDialog.getOpenFileNames( self, "%s - Add Media File" % APP_NAME, path, "Media files (%s)" % (format_str, )) item = None numFiles = len(fnames) progress_bar = QProgressDialog('Importing files...', 'Cancel import', 0, numFiles, self) for fname, c in zip(fnames, range(numFiles)): if len(str(fname)) == 0: continue fname = str(fname) if os.path.isabs(fname): fname = os.path.relpath(fname, str(path)) for pattern in image_types: if fnmatch.fnmatch(fname.lower(), pattern): item = self.labeltool.addImageFile(fname) progress_bar.setValue(c) if item is None: return self.labeltool.addVideoFile(fname) progress_bar.close() return item
def loadProject(self, project): """ Load a project into the application. """ roam.utils.log(project) roam.utils.log(project.name) roam.utils.log(project.projectfile) roam.utils.log(project.valid) (passed, message) = project.onProjectLoad() if not passed: self.bar.pushMessage("Project load rejected", "Sorry this project couldn't" "be loaded. Click for me details.", QgsMessageBar.WARNING, extrainfo=message) return self.actionMap.trigger() self.close_project() # No idea why we have to set this each time. Maybe QGIS deletes it for # some reason. self.badLayerHandler = BadLayerHandler(callback=self.missingLayers) QgsProject.instance().setBadLayerHandler(self.badLayerHandler) # Project loading screen self.stackedWidget.setCurrentIndex(3) self.projectloading_label.setText("Project {} Loading".format( project.name)) pixmap = QPixmap(project.splash) w = self.projectimage.width() h = self.projectimage.height() self.projectimage.setPixmap(pixmap.scaled(w, h, Qt.KeepAspectRatio)) QApplication.processEvents() QDir.setCurrent(os.path.dirname(project.projectfile)) fileinfo = QFileInfo(project.projectfile) QgsProject.instance().read(fileinfo)
def _read_project(self, readFilePath): """ This function does the hard work for opening a sconcho project file. """ (status, errMsg, patternGridItems, legendItems, colors, activeItem, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels) = \ io.read_project(self.settings, readFilePath) if not status: logger.error(msg.errorOpeningProjectTitle) QMessageBox.critical(self, msg.errorOpeningProjectTitle, errMsg, QMessageBox.Close) return False # add newly loaded project if not self.canvas.load_previous_pattern( self._knittingSymbols, patternGridItems, #legendItems, patternRepeats, repeatLegends, rowRepeats, textItems, rowLabels, columnLabels): return False set_up_colors(self.colorWidget, colors) self.recentlyUsedSymbolWidget.clear() #self.select_symbolSelectorItem(self.symbolSelectorWidgets, # activeItem) # provide feedback in statusbar readFileName = QFileInfo(readFilePath).fileName() self.emit(SIGNAL("update_preferences")) self.statusBar().showMessage("successfully opened " + readFileName, 3000) return True
def save(self): if self.filename.startsWith("Unnamed"): filename = QFileDialog.getSaveFileName( self, "Text Editor -- Save File As", self.filename, "Text files (*.txt *.*)") if filename.isEmpty(): return self.filename = filename self.setWindowTitle(QFileInfo(self.filename).fileName()) exception = None fh = None try: fh = QFile(self.filename) if not fh.open(QIODevice.WriteOnly): raise IOError, unicode(fh.errorString()) stream = QTextStream(fh) stream.setCodec("UTF-8") stream << self.toPlainText() self.document().setModified(False) except (IOError, OSError), e: exception = e
def load(self): """Load ?""" exception = None filehandle = None try: filehandle = QFile(self.filename) if not filehandle.open(QIODevice.ReadOnly): raise IOError, unicode(filehandle.errorString()) stream = QTextStream(filehandle) stream.setCodec("UTF-8") QApplication.processEvents() self.setPlainText(stream.readAll()) self.document().setModified(False) self.setWindowTitle(QFileInfo(self.filename).fileName()) self.loadHighlighter(self.filename) for plugin in filter_plugins_by_capability('afterFileOpen', self.enabled_plugins): plugin.do_afterFileOpen(self) except (IOError, OSError), error: exception = error
def from_file(cls, filename, canvas, relative_base=None): """ Load a project file from a path. :param filename: The path to the project file. :param canvas: (optional) Passing a canvas will auto add layers to the canvas when the load is loaded. :param relative_base_path: (optional) Relative base path for the project file to load layers from :return: A Project object which wraps QgsProject.instance() """ QgsProject.instance().clear() bridge = None if canvas: bridge = QgsLayerTreeMapCanvasBridge( QgsProject.instance().layerTreeRoot(), canvas) if relative_base is None: relative_base = os.path.dirname(filename) QDir.setCurrent(relative_base) QgsProject.instance().read(QFileInfo(filename)) if bridge: bridge.setCanvasLayers() return cls(bridge)
def run(output_file, layer_count): QgsApplication.setPrefixPath("/usr/bin/qgis", True) qgs = QgsApplication([], False) qgs.initQgis() project = QgsProject.instance() project.write(QFileInfo('/data/mock.qgs')) reg = QgsMapLayerRegistry.instance() for i in range(layer_count): vlayer = QgsVectorLayer( "/data/input.shp", "Test {}".format(i), "ogr" ) if not vlayer.isValid(): raise IOError('Layer was not valid!') reg.addMapLayer(vlayer) project.layerTreeRoot().addLayer(vlayer) project.write() qgs.exitQgis()
def chooseOutputFile(self): # get last used dir settings = QSettings() lastUsedDir = settings.value(self.lastUsedVectorDirSettingsKey, ".") # get selected filter selectedFilter = self.cboFileFormat.itemData( self.cboFileFormat.currentIndex()) # ask for a filename filename = QFileDialog.getSaveFileName( self, self.tr("Choose where to save the file"), lastUsedDir, selectedFilter) if filename == "": return # store the last used dir settings.setValue(self.lastUsedVectorDirSettingsKey, QFileInfo(filename).filePath()) self.editOutputFile.setText(filename)
def saveCurrentProject(self): origFileName = QgsProject.instance().fileName() if origFileName != "" and QgsProject.instance().isDirty(): if self.dlg.enableAlternate.isChecked(): bakFileName = origFileName + ".bak" else: bakFileName = origFileName QgsProject.instance().setFileName(bakFileName) QgsProject.instance().write(QFileInfo(bakFileName)) QgsProject.instance().setFileName(origFileName) #QgsProject.instance().dirty(0) #self.tra.ce(u"project autosaved to: "+bakFileName) if QGIS3_PLATFORM: self.iface.messageBar().pushSuccess( "Autosaver", u"project autosaved to: " + bakFileName) else: self.iface.messageBar().pushMessage( "Autosave", u"project autosaved to: " + bakFileName, level=qgis.gui.QgsMessageBar.SUCCESS, duration=3)
def updateFileMenu(self): self.fileMenu.clear() self.addActions(self.fileMenu, self.fileMenuActions[:-1]) current = (QString(self.filename) if self.filename is not None else None) recentFiles = [] for fname in self.recentFiles: if fname != current and QFile.exists(fname): recentFiles.append(fname) if recentFiles: self.fileMenu.addSeparator() for i, fname in enumerate(recentFiles): action = QAction( QIcon(":/icon.png"), "&{0} {1}".format(i + 1, QFileInfo(fname).fileName()), self) action.setData(QVariant(fname)) action.triggered.connect(self.loadFile) self.fileMenu.addAction(action) self.fileMenu.addSeparator() self.fileMenu.addAction(self.fileMenuActions[-1])
def check_for_recovery_file(filePath): """ Check for presence of recovery file. If we have one, ask we if should open if and return a tuple (status, filename of file to open). """ returnPath = (False, filePath) recoveryFilePath = generate_recovery_filepath(filePath) recoveryFile = QFile(recoveryFilePath) fileName = QFileInfo(filePath).fileName() if recoveryFile.exists(): answer = QMessageBox.question( None, msg.recoveryFilePresentTitle, msg.recoveryFilePresentText.format(fileName), QMessageBox.Ok | QMessageBox.Cancel) if (answer == QMessageBox.Ok): returnPath = (True, recoveryFilePath) return returnPath
def copyFiles(filesToCopy, out_dir): plugin_dir = pluginDir() for item in filesToCopy: dest_dir = os.path.join(out_dir, item.get("dest", "")) subdirs = item.get("subdirs", False) overwrite = item.get("overwrite", False) if debug_mode: qDebug(str(item)) qDebug("dest dir: %s" % dest_dir) # make destination directory QDir().mkpath(dest_dir) # copy files for f in item.get("files", []): fi = QFileInfo(f) dest = os.path.join(dest_dir, fi.fileName()) if fi.isRelative(): copyFile(os.path.join(plugin_dir, f), dest, overwrite) else: copyFile(f, dest, overwrite) # copy directories for d in item.get("dirs", []): fi = QFileInfo(d) source = os.path.join(plugin_dir, d) if fi.isRelative() else d dest = os.path.join(dest_dir, fi.fileName()) if subdirs: copyDir(source, dest, overwrite) else: # make destination directory QDir().mkpath(dest) # copy files in the source directory filenames = QDir(source).entryList(QDir.Files) for filename in filenames: copyFile(os.path.join(source, filename), os.path.join(dest, filename), overwrite)
def _newShapefile(self): fields = QgsFields() fields.append(QgsField('filepath', QVariant.String, '', 254)) fields.append(QgsField('filename', QVariant.String, '', 254)) fields.append(QgsField('longitude', QVariant.Double, '', 20, 7)) fields.append(QgsField('latitude', QVariant.Double, '', 20, 7)) fields.append(QgsField('altitude', QVariant.Double, '', 20, 7)) fields.append(QgsField('north', QVariant.String, '', 1)) fields.append(QgsField('azimuth', QVariant.Double, '', 20, 7)) fields.append(QgsField('gps_date', QVariant.String, '', 254)) fields.append(QgsField('img_date', QVariant.String, '', 254)) crs = QgsCoordinateReferenceSystem(4326) writer = QgsVectorFileWriter(self.shapePath, self.encoding, fields, QGis.WKBPoint, crs) del writer layer = QgsVectorLayer(self.shapePath, QFileInfo(self.shapePath).baseName(), 'ogr') return layer
def copyLayers(self): folder = self.folder layerList = self.innerLayers # A new attribute field: Surface newAttr = [QgsField('Surface', QVariant.Int)] crs = self.systemCRS newlayers = list() for layer in layerList: # Retrive the absolute path to the shapfile baseName = layer.name() path = os.path.join( folder, os.path.join('InnerLayers', str(baseName) + '.shp')) # The vector layer data type (point, line, polygon) layerType = layer.wkbType() p_fields = layer.pendingFields() layerWriter = QgsVectorFileWriter(path, "utf-8", p_fields, layerType, crs, "ESRI Shapefile") for feature in layer.getFeatures(): NewFeature = QgsFeature() # Create an empty feature NewFeature.setGeometry(feature.geometry()) # Set feature geometry NewFeature.setAttributes(feature.attributes()) # Set attributes # Update feature to the new layer layerWriter.addFeature(NewFeature) del layerWriter newlayer = QgsVectorLayer(path, QFileInfo(path).baseName(), 'ogr') newlayer.startEditing() # Add new attribute field to layer newlayer.dataProvider().addAttributes(newAttr) newlayer.commitChanges() newlayers.append(newlayer) self.newlayers = newlayers self.addNewAttr()
def _create_spatialite_db_file(self, dbPath): """Creates a SpatiaLite database file. Args: dbPath (str): A full path to the database. Returns: dbPath (str): A full path to the SpatiaLite database. """ dbInfo = QFileInfo(dbPath) sdbPath = QDir(dbInfo.absolutePath())\ .filePath(dbInfo.completeBaseName() + '.sdb') sdbInfo = QFileInfo(sdbPath) if not sdbInfo.isFile(): self.set_text_statusbar.emit( u'Importuji data do SpatiaLite databáze...', 0, False) QgsApplication.processEvents() sqliteDriver = ogr.GetDriverByName('SQLite') spatialiteDataSource = sqliteDriver.CreateDataSource( sdbPath, ['SPATIALITE=YES']) sqliteDataSource = ogr.Open(dbPath) for layerCode in ( self.dW.parLayerCode, ) + self.dW.vertexLayerCodes: originalLayer = sqliteDataSource.GetLayerByName(layerCode) copiedLayer = spatialiteDataSource.CopyLayer( originalLayer, layerCode, ['LAUNDER=NO']) sqliteDataSource.Destroy() spatialiteDataSource.Destroy() QgsApplication.processEvents() return sdbPath
def makeSieve(self): layer = self.meshLayer sievePath = os.path.join(self.outDir, 'sieve.tif') xmin = float(self.Xmin) xmax = float(self.Xmax) ymin = float(self.Ymin) ymax = float(self.Ymax) processing.runalg( 'gdalogr:rasterize', { "INPUT": layer, "FIELD": "val", "DIMENSIONS": 1, "WIDTH": float(self.settings.value('resolution')), "HEIGHT": float(self.settings.value('resolution')), "RAST_EXT": "%f,%f,%f,%f" % (xmin, xmax, ymin, ymax), "TFW": 1, "RTYPE": 4, "NO_DATA": -1, "COMPRESS": 0, "JPEGCOMPRESSION": 1, "ZLEVEL": 1, "PREDICTOR": 1, "TILED": False, "BIGTIFF": 0, "EXTRA": '', "OUTPUT": sievePath }) crs = self.crs dataset = gdal.Open(sievePath, GA_Update) # band = dataset.GetRasterBand(1) srs = osr.SpatialReference() srs.ImportFromEPSG(3826) dataset.SetProjection(srs.ExportToWkt()) # dataset = None sieveLayer = QgsRasterLayer(sievePath, QFileInfo(sievePath).baseName()) self.sieveLayer = sieveLayer self.sieveLayer.setCrs(crs)
def read_project_dialog(self): """ This function opens a read pattern dialog. """ if not self._ok_to_continue_without_saving(): return location = self.settings.export_path + "/.spf" readFilePath = \ QFileDialog.getOpenFileName(self, msg.openSconchoProjectTitle, location, ("sconcho pattern files (*.spf);;" "all files (*.*)")) if not readFilePath: return self.settings.export_path = QFileInfo(readFilePath).absolutePath() if self._read_project(readFilePath): self.set_project_save_file(readFilePath) self.update_recently_used_files(readFilePath) self.mark_project_clean()
def selectFile(self): lastDir = self.settings.value('lastShapeDir', '.') shpFilter = self.tr('ESRI Shapefiles (*.shp *.SHP)') self.encoding = self.settings.value('encoding', 'System') fileDialog = QgsEncodingFileDialog(self, self.tr('Save file'), lastDir, shpFilter, self.encoding) fileDialog.setDefaultSuffix('shp') fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(True) if fileDialog.exec_(): fileName = fileDialog.selectedFiles()[0] self.encoding = fileDialog.encoding() self.leOutputShape.setText(fileName) self.settings.setValue( 'lastShapeDir', QFileInfo(fileName).absoluteDir().absolutePath()) self.settings.setValue('encoding', self.encoding)
def loadProject(filename): # clear the map layer registry QgsMapLayerRegistry.instance().removeAllMapLayers() assert os.path.exists(filename), "project file does not exist: " + filename # load the project QgsProject.instance().read(QFileInfo(filename)) assert QgsMapLayerRegistry.instance().mapLayers( ), "no layers in map layer registry" doc = QDomDocument() with open(filename) as f: doc.setContent(f.read()) # map settings mapSettings = QgsMapSettings() mapSettings.readXML(doc.elementsByTagName("mapcanvas").at(0)) # visible layers layerIds = [] nodes = doc.elementsByTagName("legendlayer") for i in range(nodes.count()): elem = nodes.at(i).toElement().elementsByTagName("legendlayerfile").at( 0).toElement() if elem.attribute("visible") == "1": layerIds.append(elem.attribute("layerid")) mapSettings.setLayers(layerIds) # canvas color red = int( doc.elementsByTagName("CanvasColorRedPart").at(0).toElement().text()) green = int( doc.elementsByTagName("CanvasColorGreenPart").at(0).toElement().text()) blue = int( doc.elementsByTagName("CanvasColorBluePart").at(0).toElement().text()) mapSettings.setBackgroundColor(QColor(red, green, blue)) return mapSettings
def openDialog(parent, filtering="Shapefiles (*.shp *.SHP)", dialogMode="SingleFile"): settings = QSettings() dirName = settings.value("/UI/lastShapefileDir") encode = settings.value("/UI/encoding") fileDialog = QgsEncodingFileDialog( parent, QCoreApplication.translate("fTools", "Select input file") if dialogMode == "SingleFile" else QCoreApplication.translate( "fTools", "Select input files"), dirName, filtering, encode) fileDialog.setFileMode(QFileDialog.ExistingFiles) fileDialog.setAcceptMode(QFileDialog.AcceptOpen) if not fileDialog.exec_() == QDialog.Accepted: return None, None files = fileDialog.selectedFiles() settings.setValue("/UI/lastShapefileDir", QFileInfo(unicode(files[0])).absolutePath()) if dialogMode == "SingleFile": return (unicode(files[0]), unicode(fileDialog.encoding())) else: return (files, unicode(fileDialog.encoding()))
def savedlg(self): self.filename = QFileDialog.getSaveFileName( self, "Log Filename", self.settings.value('directories/dir_save', QDir.currentPath()), "Text (*.log *.txt);;All (*)") if not self.filename: return self.file = QFile(self.filename) self.lblFileName.setText(self.filename) if not self.file.open(QFile.WriteOnly): QMessageBox.warning( self, self.title, "Unable to write file {}:\n{}.".format( self.filename, self.file.errorString())) self.file = None return self.textStream = QTextStream(self.file) self.textStream.setCodec('UTF-8') self.settings.setValue('directories/dir_save', QFileInfo(self.file).path()) self.file.close()
def addImageToTable(self, file, index): image = QImage(file) if image.format() == QImage.Format_Mono: self.table.insertRow(index) self.table.setItem(index, 0, QTableWidgetItem(QFileInfo(file).fileName())) self.table.item( index, 0).setFlags(Qt.ItemIsUserCheckable | Qt.ItemIsEnabled | Qt.ItemIsSelectable) self.table.item(index, 0).setData(Qt.UserRole, image) self.table.item(index, 0).setToolTip(file) self.table.setCellWidget(index, 1, self.createColorComboBox(index)) self.table.setCellWidget(index, 2, self.createLevelComboBox(index)) self.table.setCurrentCell(index, 0) self.table.setItem( index, 3, QTableWidgetItem("{}x{}".format(image.width(), image.height()))) self.table.item(index, 3).setFlags(Qt.ItemIsSelectable) else: self.statusBar.showMessage("Tiff file not monochrome ({})".format( image.format()))
def _selectFile(self, mode='export'): settings = QSettings('Faunalia', 'landmark') lastDir = settings.value('lastZipDir', '.') if mode == 'export': fileName = QFileDialog.getSaveFileName( None, self.tr('Select file'), lastDir, self.tr('ZIP files (*.zip *.ZIP)')) else: fileName = QFileDialog.getOpenFileName( None, self.tr('Select file'), lastDir, self.tr('ZIP files (*.zip *.ZIP)')) if fileName == '': return None if not fileName.lower().endswith('.zip'): fileName += '.zip' settings.setValue('lastZipDir', QFileInfo(fileName).absoluteDir().absolutePath()) return fileName
def loadQDataStream(self): error = None fh = None try: fh = QFile(self.__fname) if not fh.open(QIODevice.ReadOnly): raise IOError(str(fh.errorString())) stream = QDataStream(fh) magic = stream.readInt32() if magic != MovieContainer.MAGIC_NUMBER: raise IOError("unrecognized file type") version = stream.readInt32() if version < MovieContainer.FILE_VERSION: raise IOError("old and unreadable file format") elif version > MovieContainer.FILE_VERSION: raise IOError("new and unreadable file format") stream.setVersion(QDataStream.Qt_4_2) self.clear(False) while not stream.atEnd(): title = QString() acquired = QDate() notes = QString() stream >> title year = stream.readInt16() minutes = stream.readInt16() stream >> acquired >> notes self.add(Movie(title, year, minutes, acquired, notes)) except EnvironmentError as e: error = "Failed to load: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Loaded {0} movie records from {1}".format( len(self.__movies), QFileInfo(self.__fname).fileName())
def selectFileName(self): if self.mLineEdit is not None: text = self.mLineEdit.text() if self.mLabel is not None: text = self.mLabel.text() fileName = QFileDialog.getOpenFileName( self.mLineEdit, QCoreApplication.translate('SimpleFilenameWidgetWrapper', 'Select a file'), QFileInfo(text).absolutePath()) if fileName.strip() == u'': return fileName = os.path.splitext(os.path.basename(fileName.strip()))[0] if self.mLineEdit is not None: self.mLineEdit.setText(fileName) if self.mLabel is not None: self.mLineEdit.setText(fileName)
def save_file(self): """ Saving file to the path where getting from QFileDialog """ fileobject = None if self.path is "": self.path = QFileDialog.getSaveFileName(self, "TextEditor", self.tr("unnamed")) try: fileobject = QFile(self.path) if not fileobject.open(QIODevice.WriteOnly): raise IOError, unicode(fileobject.errorString()) textstream = QTextStream(fileobject) textstream.setCodec("UTF-8") textstream << self.textEdit.toPlainText() self.textEdit.document().setModified(False) self.setWindowTitle("%s - TextEditor" % QFileInfo(self.path).fileName()) except (IOError, OSError), error: QMessageBox.warning( self, self.tr("TextEditor - Save Error"), self.tr("Unable to save {0}:{1}".format(self.path, error))) self.path = ""
def load_file(self): """ Loading a text file to the self.textEdit """ self.ready_to_go() fileobject = None self.path = QFileDialog.getOpenFileName(self, "TextEditor", "") try: fileobject = QFile(self.path) if not fileobject.open(QIODevice.ReadOnly): raise IOError, unicode(fileobject.errorString()) textstream = QTextStream(fileobject) textstream.setCodec("UTF-8") self.textEdit.setPlainText(textstream.readAll()) self.textEdit.document().setModified(False) print self.textEdit.document().isModified() self.setWindowTitle("%s - TextEditor" % QFileInfo(self.path).fileName()) except (IOError, OSError), error: QMessageBox.warning( self, self.tr("TextEditor - Load Error"), self.tr("Unable to load {0} : {1}".format(self.path, error))) self.path = ""
def genNodeLayer(self): crs = self.crs baseName = os.path.splitext(self.fileName)[0] path = os.path.join(self.outDir, baseName + '.shp') fields = QgsFields() for i in range(2, len(self.variables)): fieldName = self.variables[i].keys()[0] if self.variableType[i] == 'DOUBLE': fields.append(QgsField(fieldName, QVariant.Double, len=20)) elif self.variableType[i] == 'INT': fields.append(QgsField(fieldName, QVariant.Int, len=20)) writer = QgsVectorFileWriter(path, 'utf-8', fields, QGis.WKBPoint, crs, "ESRI Shapefile") Xkey = self.variables[0].keys()[0] X = self.variables[0][Xkey] Ykey = self.variables[1].keys()[0] Y = self.variables[1][Ykey] for i in range(0, len(X)): geoString = 'POINT (' + str(X[i]) + ' ' + str(Y[i]) + ')' attr = list() # for j in range(2, len(self.variables)): fieldName = self.variables[j].keys()[0] attr.append(self.variables[j][fieldName][i]) # point = QgsFeature() point.setGeometry(QgsGeometry.fromWkt(geoString)) point.setAttributes(attr) writer.addFeature(point) del writer nodeLayer = QgsVectorLayer(path, QFileInfo(path).baseName(), 'ogr') self.nodeLayer = nodeLayer
def exportXml(self, fname): error = None fh = None try: fh = QFile(fname) if not fh.open(QIODevice.WriteOnly): raise IOError(str(fh.errorString())) stream = QTextStream(fh) stream.setCodec(CODEC) stream << ("<?xml version='1.0' encoding='{0}'?>\n" "<!DOCTYPE MOVIES>\n" "<MOVIES VERSION='1.0'>\n".format(CODEC)) for key, movie in self.__movies: stream << ("<MOVIE YEAR='{0}' MINUTES='{1}' " "ACQUIRED='{2}'>\n".format(movie.year, movie.minutes, movie.acquired.toString(Qt.ISODate))) \ << "<TITLE>" << Qt.escape(movie.title) \ << "</TITLE>\n" << "<LOCATION>" if not movie.location.isEmpty(): stream << "\n" << Qt.escape(movie.location) stream << "\n</LOCATION>\n" << "<NOTES>" if not movie.notes.isEmpty(): stream << "\n" << Qt.escape(encodedNewlines(movie.notes)) stream << "\n</NOTES>\n</MOVIE>\n" stream << "</MOVIES>\n" except EnvironmentError as e: error = "Failed to export: {0}".format(e) finally: if fh is not None: fh.close() if error is not None: return False, error self.__dirty = False return True, "Exported {0} movie records to {1}".format( len(self.__movies), QFileInfo(fname).fileName())