我们从Python开源项目中,提取了以下16个代码示例,用于说明如何使用PyQt4.QtCore.QFileInfo()。
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 autosave_path(self): def check(): path = win.selectedFiles()[0] if QtCore.QFileInfo(path).permissions() & QtCore.QFile.WriteOwner: win.accept() self.autosave_path_edit.setText(path) else: QtGui.QMessageBox.warning(win, 'Write error', 'The selected path has no write permissions.') win = QtGui.QFileDialog(self, 'Select output directory') win.setFileMode(QtGui.QFileDialog.Directory) win.setOptions(QtGui.QFileDialog.ShowDirsOnly|QtGui.QFileDialog.HideNameFilterDetails) win.setAcceptMode(QtGui.QFileDialog.AcceptOpen) buttonBox = win.findChild(QtGui.QDialogButtonBox) open_btn = buttonBox.button(QtGui.QDialogButtonBox.Open) open_btn.clicked.disconnect() open_btn.clicked.connect(check) return win.exec_()
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 loadDownload(self, filepath, url, size, timestamp): """ old downloads are created when browser is opened filepath, url, size, timestamp all are str""" self.filepath = filepath self.url = url self.totalsize = size self.timestamp = timestamp self.support_resume = True fileinfo = QtCore.QFileInfo(self.filepath) self.filename = fileinfo.fileName() if fileinfo.exists(): self.loadedsize = fileinfo.size()
def startDownload(self, networkreply, filepath): """ Browser starts a new download """ self.download = networkreply self.filepath = unicode(filepath) self.timestamp = str(time.time()) self.updateMetaData() self.file = QtCore.QFile(self.filepath, self) self.loadedsize = 0 if self.support_resume == True and self.file.exists(): confirm = QtGui.QMessageBox.question(QtGui.QApplication.desktop(), "Overwrite File ?", "The file already exists.\nDo you want to Overwrite old file?", "Continue Remaining", "Replace Old", "Rename") if confirm == 0: self.download.abort() self.download.deleteLater() self.resumeDownload() elif confirm == 1: self.file.resize(0) else: self.filepath = os.path.splitext(self.filepath)[0] + '1' + os.path.splitext(self.filepath)[1] self.file = QtCore.QFile(self.filepath) else: self.file.resize(0) self.filename = QtCore.QFileInfo(self.filepath).fileName() if self.download.isFinished(): self.dataReceived() self.downloadStopped() return self.connect_signals()
def saveImageToDisk(self): """ This saves an image in page directly without downloading""" pm = self.page().mainFrame().hitTestContent(self.rel_pos).pixmap() url = self.page().mainFrame().hitTestContent(self.rel_pos).imageUrl() url.setFragment(QtCore.QString()) url.setQueryItems([]) filepath = url.toString() if QtCore.QFileInfo(filepath).suffix() not in ['jpg', 'jpeg', 'png'] : filepath = os.path.splitext(unicode(filepath))[0] + '.jpg' filepath = QtGui.QFileDialog.getSaveFileName(self, "Select Image to Save", downloaddir + QtCore.QFileInfo(filepath).fileName(), "All Images (*.jpg *.jpeg *.png);;JPEG File (*.jpg);;PNG File (*.png)" ) if not filepath.isEmpty(): if pm.save(filepath): QtGui.QMessageBox.information(self, "Successful !","Image %s \nhas been successfully saved!"%QtCore.QFileInfo(filepath).fileName())
def setInDataset(self): inName = QFileDialog.getOpenFileName(None, 'Select input dataset', '', "raster or vector (*.shp *.tif)", ) if inName: self.inDataset = QFileInfo(inName).absoluteFilePath() self.dlg.inDataset.setText(QFileInfo(inName).absoluteFilePath())
def __init__(self, mode=ALLFILE, *args, **kwargs): QtGui.QFileDialog.__init__(self, *args, **kwargs) if mode == ALLFILE: self.setNameFilters([_file_types[ALLFILE], _file_types[MIDFILE], _file_types[SYXFILE], 'Any files (*)']) else: self.setNameFilters([_file_types[mode], 'Any files (*)']) self.mode = mode self.res = None self.setWindowTitle(_titles[mode]) self.setFileMode(QtGui.QFileDialog.ExistingFile) self.setOption(QtGui.QFileDialog.HideNameFilterDetails, True) self.setAcceptMode(QtGui.QFileDialog.AcceptOpen) self.setFileMode(QtGui.QFileDialog.ExistingFile) self.setDirectory(QtCore.QDir.homePath()) urls = [] if mode == MIDFILE|SYXFILE: urls.append(_factory) if mode & MIDFILE: urls.append(_midi_sets) if mode & SYXFILE: urls.append(_single_sets) self.setSidebarUrls(urls) buttonBox = self.findChildren(QtGui.QDialogButtonBox)[0] buttonBox.removeButton(buttonBox.button(QtGui.QDialogButtonBox.Open)) self.import_btn = QtGui.QPushButton('Import') self.import_btn.clicked.connect(self.accept) self.import_btn.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DialogOpenButton)) buttonBox.addButton(self.import_btn, QtGui.QDialogButtonBox.ActionRole) self.currentChanged.connect(lambda path: self.import_btn.setText('Open' if QtCore.QFileInfo(path).isDir() else 'Import'))
def duplicate(self, uid): uid_item = self.model.findItems(uid, QtCore.Qt.MatchExactly, 4)[0] row = uid_item.row() file_info = self.model.item(row, 3).data().toPyObject() base_name = str(self.model.item(row, 0).text().toUtf8()) # base_name = str(file_info.baseName().toUtf8()) pos = 1 index = 0 while True: last = base_name[-pos] if not last.isdigit(): base_name = base_name[:-pos] + str(index) new_file_info = QtCore.QFileInfo('{}/{}'.format(file_info.absolutePath(), self.sanitize(base_name) + '.syx')) if not new_file_info.exists(): break if index == 9: pos += 1 index += 1 else: old_index = int(last) if old_index == 9: pos += 1 index = old_index + 1 base_name = base_name[:-pos] + str(index) new_file_info = QtCore.QFileInfo('{}/{}'.format(file_info.absolutePath(), self.sanitize(base_name) + '.syx')) if not new_file_info.exists(): break new_uid = str(uuid4()) current_data, current_slot, _ = self[uid] self[new_uid] = chain.from_iterable(current_data), current_slot, QtCore.QString(base_name)
def load_wave(self, path=None): if path is None: path = WaveLoad(self.main).exec_() if not path: return if self.wave_model.findItems(path, column=1): QtGui.QMessageBox.information(self, 'File already imported', 'The selected file is already in the wave list.') return stream = wave.open(str(path.toUtf8())) info = QtCore.QFileInfo(path) item = QtGui.QStandardItem(info.fileName()) item.setData(path, pathRole) item.setData(stream, streamRole) item.setData(1., gainRole) if stream.getnchannels() > 1: item.setData(True, balanceActiveRole) item.setData(0, balanceModeRole) item.setData(50, balanceValueRole) item.setData(.5, balanceLeftRole) item.setData(.5, balanceRightRole) path_item = QtGui.QStandardItem(path) self.wave_model.appendRow([item, path_item]) self.setWaveSource(item, force=True) self.wave_list.selectionModel().select(self.wave_model.index(self.wave_model.rowCount()-1, 0), QtGui.QItemSelectionModel.ClearAndSelect) self.wave_panel.setEnabled(True) self.del_wave_btn.setEnabled(True) if self.wavesource_toggle.isVisible(): self.splitter.moveSplitter(60, 0)
def load_isochrone_map(self, base_path): """Load the isochrone map in the qgis :param base_path: Output path where layers are :type base_path:str """ if not os.path.exists(base_path): message = self.tr("Error, failed to load the isochrone map") raise FileMissingError(message) else: for layer in os.listdir(base_path): layer_name = QFileInfo(layer).baseName if file.endswith(".asc"): self.iface.addRasterLayer(file, layer_name) continue elif file.endswith(".shp"): self.iface.addVectorLayer(file, layer_name, 'ogr') continue else: continue canvas_srid = self.canvas.mapRenderer().destinationCrs().srsid() on_the_fly_projection = self.canvas.hasCrsTransformEnabled() if canvas_srid != 4326 and not on_the_fly_projection: if QGis.QGIS_VERSION_INT >= 20400: self.canvas.setCrsTransformEnabled(True) else: display_warning_message_box( self.iface, self.tr('Enable \'on the fly\''), self.tr( 'Your current projection is different than EPSG:4326.' 'You should enable \'on the fly\' to display ' 'correctly the isochrone map') )
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 addPhoto(self): if self.landmarkId is not None: settings = QSettings('MatsueGkukan', 'Gkukandb') lastDir = settings.value('lastPhotoDir', '.') fileName = QFileDialog.getOpenFileName( self, self.tr('Select photo'), lastDir, self._createFilter()) if fileName == '': return settings.setValue('lastPhotoDir', QFileInfo(fileName).absoluteDir().absolutePath()) projectPath =self.GetPhotoFolderPath()+os.sep photoPath = os.path.basename(fileName) photoDate = self._photoDate(fileName).toString('yyyy-MM-dd') if not self.openDatabase(): return self.query.prepare('INSERT INTO t_photo("cdate", "filename", "landmark_id",lon,lat,angle,geomtype,geom) VALUES(?, ?, ?,?,?,?,?,?);') self.query.addBindValue(photoDate) self.query.addBindValue(photoPath) self.query.addBindValue(self.landmarkId) self.query.addBindValue(0) self.query.addBindValue(0) self.query.addBindValue(0) self.query.addBindValue(0) self.query.addBindValue('010100000000000000000000000000000000000000') if self.query.exec_(): self._copyPhotoToFolder(fileName,self.landmarkId) self.populatePhotos(-1) else: a= self.query.lastError().text() self.db.close() else: self.landmarkMessage.emit(self.tr('Select landmark before adding a photo.'), QgsMessageBar.WARNING)
def accept(self): if not self.selectedFiles(): return path = self.selectedFiles()[0] stats = QtCore.QFileInfo(path) if stats.isDir(): self.setDirectory(path) return if not stats.exists(): return if self.mode & MIDFILE: sound_list = [] try: pattern = midifile.read_midifile(str(path.toUtf8())) for track in pattern: for event in track: if isinstance(event, midifile.SysexEvent) and len(event.data) == 392: sound_list.append(Sound(event.data[6:391])) if sound_list: self.res = sound_list, path return QtGui.QFileDialog.accept(self) elif self.mode == MIDFILE: nomidi_msgbox(self) return except: if self.mode == MIDFILE: nomidi_msgbox(self) return if self.mode & SYXFILE: try: with open(str(path.toUtf8()), 'rb') as sf: sysex = list(ord(i) for i in sf.read()) if len(sysex) == 392: self.res = Sound(sysex[5:-2]), path return QtGui.QFileDialog.accept(self) elif len(sysex) == 26240 and (sysex[1:3] == [IDW, IDE] and sysex[4] == WTBD and sysex[7] == 0): self.res = Wavetable(sysex), return QtGui.QFileDialog.accept(self) elif self.mode == SYXFILE: nosysex_msgbox(self) return except: if self.mode == SYXFILE: nosysex_msgbox(self) return none_msgbox(self) return
def load_wavetable(self, as_new=False): path = QtGui.QFileDialog.getOpenFileName(self, 'Import Wavetable', filter = 'Wavetable files (*.mid, *.syx)(*.mid *.syx);;SysEx files (*.syx);;MIDI files (*.mid);;All files (*)') if not path: return try: pattern = midifile.read_midifile(str(path.toUtf8())) if len(pattern) < 1: raise InvalidException('Empty MIDI file') track = pattern[0] if len(track) < 64: raise InvalidException('MIDI file too small') wt_list = [] #todo: check for actual wave number order? for event in track: if isinstance(event, midifile.SysexEvent) and len(event.data) == 410: data = event.data[2:-1] if data[:2] != [IDW, IDE] and data[3] != WTBD and data[6] != 0: raise InvalidException wt_list.append(data[7:391]) if len(wt_list) != 64: raise InvalidException('Wrong number of SysEx events') except InvalidException as error: invalid_msgbox(self, error) return except Exception: try: with open(str(path.toUtf8()), 'rb') as sf: sysex_list = list(ord(i) for i in sf.read()) if len(sysex_list) != 26240: raise wt_list = [] for w in xrange(64): data = sysex_list[w * 410 + 1:w * 410 + 408] if data[:3] != [IDW, IDE] and data[3] != WTBD and data[6] != 0: raise wt_list.append(data[7:391]) except: invalid_msgbox(self) return wt_slot = data[4] wt_name = ''.join([str(unichr(l)) for l in data[391:405]]) self.slot_spin.setValue(wt_slot) self.name_edit.setText(wt_name) if not as_new: self.undo_push(WAVETABLE_IMPORT, True, self.waveobj_list, QtCore.QFileInfo(path).fileName()) for w, wave_obj in enumerate(self.waveobj_list): values_iter = iter(wt_list[w]) values = [] for s in xrange(128): value = (values_iter.next() << 14) + (values_iter.next() << 7) + values_iter.next() if value >= 1048576: value -= 2097152 values.append(value) wave_obj.setValues(values) if not as_new: self.undo_push(WAVETABLE_IMPORT, False, self.waveobj_list, '') self.setWave(self.waveobj_list[self.currentWave])
def resolve_path(path, collection_path, search_paths): """Try to resolve the SVG and image path. This is the procedure to check it by order: * It might be a full local path, check if it exists * It might be a url (either local file system or http(s)) * Check in the 'svg' collection path * Check in the 'image' collection path * Check in the search_paths :param path: The original path. :type path: str :param collection_path: The downloaded collection path in local. :type collection_path: str :param search_paths: List of paths to search the image/svg path :type search_paths: str """ # It might be a full path if QFile(path).exists(): return QFileInfo(path).canonicalFilePath() # It might be a url if '://'in path: url = QUrl(path) if url.isValid() and url.scheme() != '': if url.scheme().lower() == 'file': # It's a url to local file path = url.toLocalFile() if QFile(path).exists(): return QFileInfo(path).canonicalFilePath() else: # URL to pointing to online resource return path # Check in the svg collection path file_name = path_leaf(path) svg_collection_path = os.path.join(collection_path, 'svg', file_name) if QFile(svg_collection_path).exists(): return QFileInfo(svg_collection_path).canonicalFilePath() # Check in the image collection path image_collection_path = os.path.join(collection_path, 'image', file_name) if QFile(image_collection_path).exists(): return QFileInfo(image_collection_path).canonicalFilePath() # Still not found, check in the search_paths for search_path in search_paths: local_path = os.path.join(search_path, path) if QFile(local_path).exists(): return QFileInfo(local_path).canonicalFilePath() # Can't find any, just return the original path return path