def __init__(self, iface): self.dock = None self.results = [] # Save reference to the QGIS interface self.iface = iface self.iface.newProjectCreated.connect(self._hideMarker) self.iface.projectRead.connect(self._hideMarker) self.canvas = self.iface.mapCanvas() self.marker = QgsVertexMarker(self.iface.mapCanvas()) self.marker.setIconSize(20) self.marker.setPenWidth(3) self.marker.setIconType(QgsVertexMarker.ICON_CROSS) self.marker.hide() # Create the dialog and keep reference self.widget = gazetteerSearchDialog() self.widget.runSearch.connect(self.runSearch) self.widget.ui.clearButton.pressed.connect(self.clearResults) self.widget.zoomRequested.connect(self.zoomTo) # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/gazetteersearch" # initialize locale localePath = "" if QGis.QGIS_VERSION_INT < 10900: locale = QSettings().value("locale/userLocale").toString()[0:2] else: locale = QSettings().value("locale/userLocale")[0:2] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/gazetteersearch_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def handler(self, title): """Maneja el evento de click sobre cualquiera de los botones de cargar archivo, con el fin de abrir un diálogo que le permita al usuario seleccionar el archivo de su sistema de archivos.""" layerPath = QFileDialog.getSaveFileName(self, u'Crear archivo xls', '.', 'Archivo Excel (*.xls)') layerInfo = QFileInfo(layerPath) if layerPath == "" : return if len(layerInfo.fileName()) < 5: layerPath += ".xls" elif layerInfo.fileName()[-4: ] != ".xls": layerPath += ".xls" self.lineEditPath.setText(layerPath)
def dirButton(self): """Get the destination file, where captured coordinates are saved.""" self.namedir = QFileDialog.getSaveFileName( self.dlg, self.tr(u"Select destination file"), QFileInfo( QgsProject.instance().fileName()).fileName().split('.')[0] + '.txt', '*.txt') self.dlg.dir_name.setText(self.namedir) # Enable the saveButton if file is chosen if not self.dlg.dir_name.text(): self.dlg.saveButton.setEnabled(False) else: self.dlg.saveButton.setEnabled(True)
def render(self, fileName): if self.m_mainFrame.contentsSize() == '': return False fileInfo = QFileInfo(fileName) path = QDir() path.mkpath(fileInfo.absolutePath()) if fileName.lower().endswith('.pdf'): return self.renderPdf(fileName) image = self.renderImage() return image.save(fileName)
def __init__(self, iface): self.iface = iface self.mapCanvas = iface.mapCanvas() # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/intersectit" systemPluginPath = QgsApplication.prefixPath( ) + "/share/qgis/python/plugins/intersectit" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] pluginPath = "" # default case if QFileInfo(userPluginPath).exists(): pluginPath = '{}/i18n/intersectit_{}.qm'.format( userPluginPath, myLocale) elif QFileInfo(systemPluginPath).exists(): pluginPath = '{}/i18n/intersectit_{}.qm'.format( systemPluginPath, myLocale) self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def do_ftp_put(self): num = len(self.files) for i in range(num): file = self.files[i] fhandle = QFile(file) fhandle.open(QIODevice.ReadOnly) byte_array = QByteArray() byte_array.append(fhandle.readData(fhandle.size())) fileinfo = QFileInfo(file) filename = fileinfo.fileName() self.ftp.put(byte_array, filename) self.ftp.close()
def make_pdf(xmin, ymin, xmax, ymax, filter_expression): canvas = QgsMapCanvas() # Load our project QgsProject.instance().read(QFileInfo(project_path)) # Set canvas extent canvas.setExtent(QgsRectangle(xmin, ymin, xmax, ymax)) # Load layers here if they are not already in the project for layer in QgsMapLayerRegistry.instance().mapLayers().values(): if layer.name() == 'data': lyr = layer break lyr.setSubsetString(filter_expression) # bridge used in standalone script: http://docs.qgis.org/testing/en/docs/pyqgis_developer_cookbook/loadproject.html bridge = QgsLayerTreeMapCanvasBridge(QgsProject.instance().layerTreeRoot(), canvas) bridge.setCanvasLayers() # Check data providers load ok print('Provider List') print(QgsProviderRegistry.instance().providerList()) # Print layer validity - I've had some trouble with some wms layers for layer in QgsMapLayerRegistry.instance().mapLayers().values(): print(layer.name()) print(layer.isValid()) template_file = file(template_path) template_content = template_file.read() template_file.close() document = QDomDocument() document.setContent(template_content) composition = QgsComposition(canvas.mapSettings()) # You can use this to replace any string like this [key] # in the template with a new value. e.g. to replace # [date] pass a map like this {'date': '1 Jan 2012'} substitution_map = {'title': 'the title of my map'} composition.loadFromTemplate(document, substitution_map) # You must set the id in the template map_item = composition.getComposerItemById('Main Map') map_item.setMapCanvas(canvas) map_item.zoomToExtent(canvas.extent()) # You must set the id in the template legend_item = composition.getComposerItemById('Legend') legend_item.updateLegend() composition.refreshItems() composition.exportAsPDF('export.pdf') QgsProject.instance().clear()
def getFileInfo(image): def prepareFileTMS(url_tms): def createLocalFile(): def populateLocalFile(): html = response.read() response.close() fw = open(localName, 'w') fw.write(html) fw.close() isOk = True try: response = urllib2.urlopen(url_tms) except urllib2.HTTPError, e: isOk = False except urllib2.URLError, e: isOk = False # if not isOk: return QFileInfo(url_tms) # Add for error list else: populateLocalFile() return QFileInfo(localName)
def copyFile(source, dest, overwrite=False): if os.path.exists(dest): if overwrite or abs( QFileInfo(source).lastModified().secsTo( QFileInfo(dest).lastModified()) ) > 5: # use secsTo for different file systems if debug_mode: qDebug("Existing file removed: %s (%s, %s)" % (dest, str(QFileInfo(source).lastModified()), str(QFileInfo(dest).lastModified()))) QFile.remove(dest) else: if debug_mode: qDebug("File already exists: %s" % dest) return False ret = QFile.copy(source, dest) if debug_mode: if ret: qDebug("File copied: %s to %s" % (source, dest)) else: qDebug("Failed to copy file: %s to %s" % (source, dest)) return ret
def __init__(self, iface): # Save reference to the QGIS interface self.outdir = '' self.ilayers = QgsMapLayerRegistry.instance() self.iface = iface # initialize plugin directory self.plugin_dir = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/kuw_filter" # initialize locale localePath = "" locale = QSettings().value("locale/userLocale")[0:5] if QFileInfo(self.plugin_dir).exists(): localePath = self.plugin_dir + "/i18n/kuw_filter_" + locale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator) # Create the dialog (after translation) and keep reference self.dlg = kuw_filterDialog()
def __init__(self, iface): self.iface = iface self.mapCanvas = iface.mapCanvas() memLay = MemoryLayers(iface) self.lineLayer = memLay.lineLayer self.pointLayer = memLay.pointLayer # Initialise the translation environment. userPluginPath = QFileInfo(QgsApplication.qgisUserDbFilePath()).path( ) + "/python/plugins/intersectit" systemPluginPath = QgsApplication.prefixPath( ) + "/share/qgis/python/plugins/intersectit" locale = QSettings().value("locale/userLocale") myLocale = locale[0:2] if QFileInfo(userPluginPath).exists(): pluginPath = userPluginPath + "/i18n/intersectit_" + myLocale + ".qm" elif QFileInfo(systemPluginPath).exists(): pluginPath = systemPluginPath + "/i18n/intersectit_" + myLocale + ".qm" self.localePath = pluginPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def create_form(self): """ Create an XML file that will be our XFORM Document for reading and writing We want a new file when everytime we are creating XForm type: file :return: file """ self.form = QFile(os.path.join(FORM_HOME, self.form_name())) if not QFileInfo(self.form).suffix() == DOCEXTENSION: self.form_name() if not self.form.open(QIODevice.ReadWrite | QIODevice.Truncate | QIODevice.Text): return self.form.OpenError
def on_actionOpen_file_triggered(self): file_dialog = QFileDialog( self, self.tr("Open file(s)..."), filter=self. tr("FITS files (*.fit *.dst *.fits *.fts *.lilo *.lihi *.silo *.sihi *.mxlo *.mxhi *.rilo *.rihi *.vdlo *.vdhi)" )) file_dialog.setFileMode(QFileDialog.ExistingFile) files = file_dialog.getOpenFileNames() if files: for file_ in files: file_info = QFileInfo(file_) file_path = str(file_info.filePath()) self.add_tab(file_path, file_info.fileName())
def __init__(self, iface): QObject.__init__(self) # Save reference to the QGIS interface self.iface = iface self.canvas = self.iface.mapCanvas() self.w = None self.vsCheck = None self.layer_list = [] #Initialise thetranslation environment self.plugin_path = QDir.cleanPath( os.path.abspath(os.path.dirname(__file__))) myLocaleName = QLocale.system().name() myLocale = myLocaleName[0:2] if QFileInfo(self.plugin_path).exists(): localePath = self.plugin_path + "/i18n/pgVersion_" + myLocale + ".qm" if QFileInfo(localePath).exists(): self.translator = QTranslator() self.translator.load(localePath) if qVersion() > '4.3.3': QCoreApplication.installTranslator(self.translator)
def _updateRecentFileActions(self): files = list(self.settings.value("recentFileList").toStringList()) fileNames = {} numRecentFiles = min(len(files), self.MaxRecentFiles) for action in self.recentFileActions: action.setVisible(False) for i in range(numRecentFiles): fileName = QFileInfo(files[i]).fileName() if fileName in fileNames.keys(): fileNames[fileName] += 1 else: fileNames[fileName] = 1 for i in range(numRecentFiles): fileName = QFileInfo(files[i]).fileName() filePath = QVariant(files[i]) action = self.recentFileActions[i] action.setText(fileNames[fileName] == 1 and fileName or filePath.toString()) action.setData(filePath) action.setVisible(True) self.emit(SIGNAL("recentFileActionsAvailable(bool)"), numRecentFiles > 0)
def setFile(self, dfile, source_entity, doc_type, doc_type_id): """ Set the absolute file path including the name, that is to be associated with the document widget. """ if self._mode == UPLOAD_MODE: self.fileInfo = QFileInfo(dfile) self._displayName = unicode(self.fileInfo.fileName()) self._docSize = self.fileInfo.size() self._source_entity = source_entity self._doc_type = doc_type self._doc_type_id = doc_type_id self.uploadDoc() self.buildDisplay()
def handler(self, title): """Maneja el evento de click sobre cualquiera de los botones de cargar archivo, con el fin de abrir un diálogo que le permita al usuario seleccionar el archivo de su sistema de archivos.""" layerPath = QFileDialog.getOpenFileName(self, u'Abrir shapefile', '.', 'Shapefiles (*.shp *.tif)') layerInfo = QFileInfo(layerPath) if title == 'fondo': self.capaFondo.setText(layerPath) elif title == 'hidr': self.capaHidrografia.setText(layerPath) elif title == 'ejes': self.capaEjes.setText(layerPath) elif title == 'secc': self.capaSecciones.setText(layerPath)
def fileOpen(self): if not self.okToContinue(): return path = '.' filename = self.labeltool.getCurrentFilename() if (filename is not None) and (len(filename) > 0): path = QFileInfo(filename).path() format_str = ' '.join(self.labeltool.getAnnotationFilePatterns()) fname = QFileDialog.getOpenFileName( self, "%s - Load Annotations" % APP_NAME, path, "%s annotation files (%s)" % (APP_NAME, format_str)) if len(str(fname)) > 0: self.labeltool.loadAnnotations(fname)
def layers(self): """Return a list of layers available. :return: List of layers available in the datastore. :rtype: list .. versionadded:: 4.0 """ extensions = ['*.%s' % f for f in EXTENSIONS] self.uri.setNameFilters(extensions) files = self.uri.entryList() self.uri.setNameFilters('') files = human_sorting([QFileInfo(f).baseName() for f in files]) return files
def saveNoteAs(self): self.saveCurrentNote() fileName = QFileDialog.getSaveFileName( self, self.tr('Save as'), '', '(*.md *.mkd *.markdown);;' + self.tr('All files(*)')) if fileName == '': return if not QFileInfo(fileName).suffix(): fileName += '.md' fh = QFile(fileName) fh.open(QIODevice.WriteOnly) savestream = QTextStream(fh) savestream << self.notesEdit.toPlainText() fh.close()
def generate_recovery_filepath(filePath): """ Based on a filePath generate the name for the recovery File. """ # check if sconcho directory in user's home directory exists sconchoDirName = QDir.homePath() + "/.sconcho" sconchoDir = QDir(sconchoDirName) if not sconchoDir.exists(): status = sconchoDir.mkdir(sconchoDirName) recoveryFileInfo = QFileInfo(filePath) recoveryFilePath = sconchoDirName + "/" + \ recoveryFileInfo.fileName() + ".recovery" return recoveryFilePath
def saveDialog(parent, filtering="Shapefiles (*.shp *.SHP)"): settings = QSettings() dirName = settings.value("/UI/lastShapefileDir") encode = settings.value("/UI/encoding") fileDialog = QgsEncodingFileDialog(parent, QCoreApplication.translate("fTools", "Save output shapefile"), dirName, filtering, encode) fileDialog.setDefaultSuffix("shp") fileDialog.setFileMode(QFileDialog.AnyFile) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(True) if not fileDialog.exec_() == QDialog.Accepted: return None, None files = fileDialog.selectedFiles() settings.setValue("/UI/lastShapefileDir", QFileInfo(unicode(files[0])).absolutePath()) return (unicode(files[0]), unicode(fileDialog.encoding()))
def getShortcutIcon(shortcut): if shortcut["icon"]: icon = QIcon(shortcut["icon"]) if not icon.isNull(): return icon iconProvider = QFileIconProvider() if shortcut["path"] == COMPUTER_PATH: return QIcon(":/images/user-home.png") elif shortcut["path"] == DOCUMENTS_PATH: documentsIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation))) if documentsIcon.isNull(): return QIcon(":/images/folder-documents.png") else: return documentsIcon elif shortcut["path"] == MUSIC_PATH: musicIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.MusicLocation))) if musicIcon.isNull(): return QIcon(":/images/folder-sound.png") else: return musicIcon elif shortcut["path"] == PICTURES_PATH: picturesIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.PicturesLocation))) if picturesIcon.isNull(): return QIcon(":/images/folder-image.png") else: return picturesIcon else: url = QUrl.fromUserInput(shortcut["path"]) if url.scheme() == "file": if os.path.exists(shortcut["path"]): icon = iconProvider.icon(QFileInfo(url.toLocalFile())) if not icon.isNull(): return icon return QIcon(":/images/unknown.png") else: return QIcon(":/images/httpurl.png") return QIcon(":/images/unknown.png")
def __init__(self, dimension=2, probability=0.95, stdev_angle=3, stdev_dist=3, stdev_dist1=3): """ Initialize a new GamaInterface instance. :param dimension: dimension of network (int), 1/2/3 :param probability: porbability for statistical tests (float) :param stdev_angle: standard deviation for directions in cc (float) :param stdev_dist: base standard deviation for distances mm (float) :param stdev_dist1: standard deviation for distances mm/km (float) """ self.dimension = dimension self.probability = probability self.stdev_angle = stdev_angle self.stdev_dist = stdev_dist self.stdev_dist1 = stdev_dist1 self.points = [] self.observations = [] gama_path = QSettings().value("SurveyingCalculation/gama_path", config.gama_path) if QFileInfo(gama_path).exists(): gama_prog = gama_path else: # get operating system dependent file name of gama_local plugin_dir = QDir().cleanPath(QFileInfo(__file__).absolutePath()) gama_prog = QDir(plugin_dir).absoluteFilePath("gama-local") if not QFileInfo(gama_prog).exists(): if QFileInfo(gama_prog + ".exe").exists(): gama_prog += '.exe' elif QFileInfo(gama_prog + "64.exe").exists(): gama_prog += '64.exe' else: gama_prog = None self.gama_prog = gama_prog
def __init__(self, iface): if not valid: return # Save reference to the QGIS interface self.iface = iface try: self.QgisVersion = unicode(QGis.QGIS_VERSION_INT) except: self.QgisVersion = unicode(QGis.qgisVersion)[0] if QGis.QGIS_VERSION[0:3] < "1.5": # For i18n support userPluginPath = qgis.utils.home_plugin_path + "/GdalTools" systemPluginPath = qgis.utils.sys_plugin_path + "/GdalTools" overrideLocale = QSettings().value("locale/overrideFlag", False, type=bool) if not overrideLocale: localeFullName = QLocale.system().name() else: localeFullName = QSettings().value("locale/userLocale", "", type=str) if QFileInfo(userPluginPath).exists(): translationPath = userPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" else: translationPath = systemPluginPath + "/i18n/GdalTools_" + localeFullName + ".qm" self.localePath = translationPath if QFileInfo(self.localePath).exists(): self.translator = QTranslator() self.translator.load(self.localePath) QCoreApplication.installTranslator(self.translator)
def Restaurer_Projet(self): dlg = QFileDialog() dlg.setFileMode(QFileDialog.AnyFile) dlg.setFilter("Text files (*.qgs)") filenames = [] if dlg.exec_(): filenames = dlg.selectedFiles() try: project = QgsProject.instance() project.read(QFileInfo(filenames[0])) QMessageBox.information(None, "information", " l'importer Votre projet est reussite") except: QMessageBox.critical(None, "Erreur", "impossible d'importer Votre projet")
def chooseInputFile(self): vectorFormats = qgis.core.QgsProviderRegistry.instance().fileVectorFilters() # get last used dir and format settings = QSettings() lastDir = settings.value("/db_manager/lastUsedDir", "") lastVectorFormat = settings.value("/UI/lastVectorFileFilter", "") # ask for a filename (filename, lastVectorFormat) = QFileDialog.getOpenFileNameAndFilter(self, self.tr("Choose the file to import"), lastDir, vectorFormats, lastVectorFormat) if filename == "": return # store the last used dir and format settings.setValue("/db_manager/lastUsedDir", QFileInfo(filename).filePath()) settings.setValue("/UI/lastVectorFileFilter", lastVectorFormat) self.cboInputLayer.setEditText( filename )
def dirDialog(parent): settings = QSettings() dirName = settings.value("/UI/lastShapefileDir") encode = settings.value("/UI/encoding") fileDialog = QgsEncodingFileDialog(parent, "Save output shapefile", dirName, encode) fileDialog.setFileMode(QFileDialog.DirectoryOnly) fileDialog.setAcceptMode(QFileDialog.AcceptSave) fileDialog.setConfirmOverwrite(False) if not fileDialog.exec_() == QDialog.Accepted: return None, None folders = fileDialog.selectedFiles() settings.setValue("/UI/lastShapefileDir", QFileInfo(unicode(folders[0])).absolutePath()) return (unicode(folders[0]), unicode(fileDialog.encoding()))
def _get_plugin_path(self): """Prompt the user for the path where the plugin should be written to. """ while not QFileInfo(self.plugin_path).isWritable(): # noinspection PyTypeChecker,PyArgumentList QMessageBox.critical( None, 'Error', 'Directory is not writeable') # noinspection PyCallByClass,PyTypeChecker self.plugin_path = QFileDialog.getExistingDirectory( self.dialog, 'Select the Directory for your Plugin', self._last_used_path()) if self.plugin_path == '': return False return True
def openDialog( parent, filtering="GPX (*.gpx)", dialogMode="SingleFile"): settings = QSettings() dirName = settings.value( "/UI/lastShapefileDir" ) encode = settings.value( "/UI/encoding" ) fileDialog = QgsEncodingFileDialog( parent, "Save output file", 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() ) )