def __setFileName(self, fileName): """ Private method to set the file name to save the download into. @param fileName name of the file to save into @type str """ fileInfo = QFileInfo(fileName) WebBrowserWindow.downloadManager().setDownloadDirectory( fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText( self.tr("Download directory ({0}) couldn't be created."). format(saveDirPath.absolutePath())) self.__setDateTime() return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName())
def saveImage(self): """ Provides a dialog window to allow the user to save the image file. """ imageFile, _ = QFileDialog.getSaveFileName( self, "Choose a filename to save the image", "", "Images (*.png)") info = QFileInfo(imageFile) if info.baseName() != "": newImageFile = QFileInfo(info.absoluteDir(), info.baseName() + ".png").absoluteFilePath() if not self.finalWidget.pixmap().save(newImageFile, "PNG"): QMessageBox.warning( self, "Cannot save file", "The file could not be saved.", QMessageBox.Cancel, QMessageBox.NoButton, QMessageBox.NoButton, ) else: QMessageBox.warning( self, "Cannot save file", "Please enter a valid filename.", QMessageBox.Cancel, QMessageBox.NoButton, QMessageBox.NoButton, )
def _copy_file(self, uid: str = "", source_path: str = "", dest_path: str = ""): self._current_uid = uid source_file = QFile(source_path) dest_file = QFile(dest_path) if not source_file.open(QFile.ReadOnly): self.copy_error.emit(uid, FileCopier.CannotOpenSourceFile) return dest_file_info = QFileInfo(dest_file) dest_dir = dest_file_info.absoluteDir() if not dest_dir.exists(): if not dest_dir.mkpath(dest_dir.absolutePath()): self.copy_error.emit(uid, FileCopier.CannotCreateDestinationDirectory) return if not dest_file.open(QFile.WriteOnly): ic(dest_path, dest_file.errorString()) self.copy_error.emit(uid, FileCopier.CannotOpenDestinationFile) return progress: int = 0 total: int = source_file.size() error: int = FileCopier.NoError while True: if self._cancel_current: self._cancel_current = False self.copy_cancelled.emit(uid) break data: Union[bytes, int] = source_file.read(_COPY_BLOCK_SIZE) if isinstance(data, int): assert data == -1 error = FileCopier.CannotReadSourceFile break data_len = len(data) if data_len == 0: self.copy_progress.emit(uid, progress, total) break if data_len != dest_file.write(data): error = FileCopier.CannotWriteDestinationFile break progress += data_len self.copy_progress.emit(uid, progress, total) qApp.processEvents() source_file.close() dest_file.close() if error != FileCopier.NoError: dest_file.remove() self.copy_error.emit(uid, error) else: dest_file.setPermissions(source_file.permissions()) self.copy_complete.emit(uid)
def checkValidOutputDir(self, text): if not text: return fileInfo = QFileInfo(self.mOutputFileLineEdit.text()) #enable ok button only if save directory exists self.mButtonBox.button(QDialogButtonBox.Ok).setEnabled( fileInfo.absoluteDir().exists())
def FilePath(self, filename=""): path = QDir.currentPath() if filename == "": if self.fileHandler != None: filename = self.fileHandler.fileName if filename != "": fInfo = QFileInfo(filename) qPath = fInfo.absoluteDir() if qPath.exists(): path = qPath.absolutePath() return path
def saveImage(): info = QFileInfo(ModifyProfile.imageFile) if info.baseName() != '': newImageFile = QFileInfo(info.absoluteDir(), 'profile_' + '.png').absoluteFilePath() #model.User.u_id() Communication.profile(info.absoluteDir()) if not ModifyProfile.label_img.pixmap().save(newImageFile, 'PNG'): QtWidgets.QMessageBox.warning(ModifyProfile.qwidget, "Cannot save file", "The file could not be saved.", QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.NoButton, QtWidgets.QMessageBox.NoButton) else: QtWidgets.QMessageBox.warning(ModifyProfile.qwidget, "Cannot save file", "Please enter a valid filename.", QtWidgets.QMessageBox.Cancel, QtWidgets.QMessageBox.NoButton) ModifyProfile.widget_hide()
def __add_layer_definition_file(self, file_name, root_group): """ shamelessly copied from https://github.com/qgis/QGIS/blob/master/src/core/qgslayerdefinition.cpp """ qfile = QFile(file_name) if not qfile.open(QIODevice.ReadOnly): return None doc = QDomDocument() if not doc.setContent(qfile): return None file_info = QFileInfo(qfile) QDir.setCurrent(file_info.absoluteDir().path()) root = QgsLayerTreeGroup() ids = doc.elementsByTagName('id') for i in range(0, ids.size()): id_node = ids.at(i) id_elem = id_node.toElement() old_id = id_elem.text() layer_name = old_id[:-17] date_time = QDateTime.currentDateTime() new_id = layer_name + date_time.toString('yyyyMMddhhmmsszzz') id_elem.firstChild().setNodeValue(new_id) tree_layer_nodes = doc.elementsByTagName('layer-tree-layer') for j in range(0, tree_layer_nodes.count()): layer_node = tree_layer_nodes.at(j) layer_elem = layer_node.toElement() if old_id == layer_elem.attribute('id'): layer_node.toElement().setAttribute('id', new_id) layer_tree_elem = doc.documentElement().firstChildElement( 'layer-tree-group') load_in_legend = True if not layer_tree_elem.isNull(): root.readChildrenFromXML(layer_tree_elem) load_in_legend = False layers = QgsMapLayer.fromLayerDefinition(doc) QgsProject.instance().addMapLayers(layers, load_in_legend) nodes = root.children() for node in nodes: root.takeChild(node) del root root_group.insertChildNodes(-1, nodes) return None
def saveImage(self): """ Provides a dialog window to allow the user to save the image file. """ imageFile, _ = QFileDialog.getSaveFileName(self, "Choose a filename to save the image", "", "Images (*.png)") info = QFileInfo(imageFile) if info.baseName() != '': newImageFile = QFileInfo(info.absoluteDir(), info.baseName() + '.png').absoluteFilePath() if not self.finalWidget.pixmap().save(newImageFile, 'PNG'): QMessageBox.warning(self, "Cannot save file", "The file could not be saved.", QMessageBox.Cancel, QMessageBox.NoButton, QMessageBox.NoButton) else: QMessageBox.warning(self, "Cannot save file", "Please enter a valid filename.", QMessageBox.Cancel, QMessageBox.NoButton, QMessageBox.NoButton)
def __getFileName(self): """ Private method to get the file name to save to from the user. """ if self.__gettingFileName: return import Helpviewer.HelpWindow downloadDirectory = Helpviewer.HelpWindow.HelpWindow\ .downloadManager().downloadDirectory() if self.__fileName: fileName = self.__fileName originalFileName = self.__originalFileName self.__toDownload = True ask = False else: defaultFileName, originalFileName = \ self.__saveFileName(downloadDirectory) fileName = defaultFileName self.__originalFileName = originalFileName ask = True self.__autoOpen = False if not self.__toDownload: from .DownloadAskActionDialog import DownloadAskActionDialog url = self.__reply.url() dlg = DownloadAskActionDialog( QFileInfo(originalFileName).fileName(), self.__reply.header(QNetworkRequest.ContentTypeHeader), "{0}://{1}".format(url.scheme(), url.authority()), self) if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return if dlg.getAction() == "scan": self.__mainWindow.requestVirusTotalScan(url) self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("VirusTotal scan scheduled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return self.__autoOpen = dlg.getAction() == "open" if PYQT_VERSION_STR >= "5.0.0": from PyQt5.QtCore import QStandardPaths tempLocation = QStandardPaths.standardLocations( QStandardPaths.TempLocation)[0] else: from PyQt5.QtGui import QDesktopServices tempLocation = QDesktopServices.storageLocation( QDesktopServices.TempLocation) fileName = tempLocation + '/' + \ QFileInfo(fileName).completeBaseName() if ask and not self.__autoOpen and self.__requestFilename: self.__gettingFileName = True fileName = E5FileDialog.getSaveFileName( None, self.tr("Save File"), defaultFileName, "") self.__gettingFileName = False if not fileName: self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}") .format(QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return fileInfo = QFileInfo(fileName) Helpviewer.HelpWindow.HelpWindow.downloadManager()\ .setDownloadDirectory(fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__output.setFileName(fileName + ".part") self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText(self.tr( "Download directory ({0}) couldn't be created.") .format(saveDirPath.absolutePath())) return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) if self.__requestFilename: self.__readyRead()
def __getFileName(self): """ Private method to get the file name to save to from the user. """ if self.__gettingFileName: return import Helpviewer.HelpWindow downloadDirectory = Helpviewer.HelpWindow.HelpWindow\ .downloadManager().downloadDirectory() if self.__fileName: fileName = self.__fileName originalFileName = self.__originalFileName self.__toDownload = True ask = False else: defaultFileName, originalFileName = \ self.__saveFileName(downloadDirectory) fileName = defaultFileName self.__originalFileName = originalFileName ask = True self.__autoOpen = False if not self.__toDownload: from .DownloadAskActionDialog import DownloadAskActionDialog url = self.__reply.url() dlg = DownloadAskActionDialog( QFileInfo(originalFileName).fileName(), self.__reply.header(QNetworkRequest.ContentTypeHeader), "{0}://{1}".format(url.scheme(), url.authority()), self) if dlg.exec_() == QDialog.Rejected or dlg.getAction() == "cancel": self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return ## if dlg.getAction() == "scan": ## self.__mainWindow.requestVirusTotalScan(url) ## ## self.progressBar.setVisible(False) ## self.__reply.close() ## self.on_stopButton_clicked() ## self.filenameLabel.setText( ## self.tr("VirusTotal scan scheduled: {0}").format( ## QFileInfo(defaultFileName).fileName())) ## self.__canceledFileSelect = True ## return ## self.__autoOpen = dlg.getAction() == "open" if PYQT_VERSION_STR >= "5.0.0": from PyQt5.QtCore import QStandardPaths tempLocation = QStandardPaths.storageLocation( QStandardPaths.TempLocation) else: from PyQt5.QtGui import QDesktopServices tempLocation = QDesktopServices.storageLocation( QDesktopServices.TempLocation) fileName = tempLocation + '/' + \ QFileInfo(fileName).completeBaseName() if ask and not self.__autoOpen and self.__requestFilename: self.__gettingFileName = True fileName = E5FileDialog.getSaveFileName(None, self.tr("Save File"), defaultFileName, "") self.__gettingFileName = False if not fileName: self.progressBar.setVisible(False) self.__reply.close() self.on_stopButton_clicked() self.filenameLabel.setText( self.tr("Download canceled: {0}").format( QFileInfo(defaultFileName).fileName())) self.__canceledFileSelect = True return fileInfo = QFileInfo(fileName) Helpviewer.HelpWindow.HelpWindow.downloadManager()\ .setDownloadDirectory(fileInfo.absoluteDir().absolutePath()) self.filenameLabel.setText(fileInfo.fileName()) self.__output.setFileName(fileName + ".part") self.__fileName = fileName # check file path for saving saveDirPath = QFileInfo(self.__fileName).dir() if not saveDirPath.exists(): if not saveDirPath.mkpath(saveDirPath.absolutePath()): self.progressBar.setVisible(False) self.on_stopButton_clicked() self.infoLabel.setText( self.tr("Download directory ({0}) couldn't be created."). format(saveDirPath.absolutePath())) return self.filenameLabel.setText(QFileInfo(self.__fileName).fileName()) if self.__requestFilename: self.__readyRead()