def open_case(self): """ Gives the user a file dialog to find their existing project and opens that. :return: None """ open_dialog = QFileDialog() user_location = open_dialog.getOpenFileName()[ 0] # Index 0 because user can't pick more than one file. if user_location == '': return # User most likely pressed cancel. case = Case.open_from_disk(user_location) if case is None: # Something bad must have happened. Tell the user that the file is corrupt. Or invalid. alert = QMessageBox() alert.setText("Corrupt case file or invalid file type.") alert.setIcon(QMessageBox.Critical) alert.exec_() return else: # Successfully open a case! case_controller = CaseController(case) self.open_window(case_controller)
def button_include_dir_handler(self): initial_dir = os.path.dirname(str(self.include_dir.text())) dirDialog = QFileDialog() dirDialog.setFileMode(QFileDialog.Directory) new_dir = dirDialog.getExistingDirectory(self, "Select directory", initial_dir) if (len(new_dir) > 0): self.include_dir.setText(new_dir)
def openFile(self): # Initialize window to show opened image self.newW = ShowOpenedImage() fileDialog = QFileDialog() fName = fileDialog.getOpenFileName(self, 'Open Image', '/', 'Image Files (*.png *.jpg *.bmp)'); print('Opened file %s' %fName[0]) self.newW.showImage(fName[0])
def image_import(self): """ Take the path(s) of one or more images and import them to the application. :return: Nothing """ file_dialog = QFileDialog() # Create QFileDialog # Open the file dialog as Open File Names dialog (for image choice) f_path = file_dialog.getOpenFileNames(parent=None, caption="Open Image(s)", directory=QDir.homePath(), filter=self.IMG_FILTER, options=self.DIALOG_FLAG)[0] if f_path: # If user chose at least one image img_id_counter = 0 # Set a counter for id for file in f_path: # For all paths in f_paths image_tmp = Image() # Create an Image object success = image_tmp.img_open(file) # Set image parameters if success: # If image exists image_tmp.img_set_image_id(img_id_counter) # Set image counter img_id_counter += 1 # increase the counter by 1 # image_tmp.img_print_info() # print image info for debugging self.image_list.append(image_tmp) # Append image to list item_name = "../" + image_tmp.info.dir_name + "/" + image_tmp.info.name # Set name for view item_widget = QListWidgetItem(item_name) # Append item to window image list item_widget.setFlags(item_widget.flags() | QtCore.Qt.ItemIsUserCheckable) # Set it checkable item_widget.setCheckState(QtCore.Qt.Checked) # Set it checked self.ui_main_win.listImage.addItem(item_widget) # Add item to list self.ui_main_win.menuCamera_Settings.setEnabled(self.UP) # Enable Camera menu self.ui_main_win.actionCrabSFM.setEnabled(self.UP) # Enable SFM action
def action_Slot(self, name): if name == "default": self.camCtr.update(reset=True) elif name == "update": self.camCtr.update() elif name == "save" or name == "load": conf_dir = os.path.join(Path.home(), ".config", "cam_control") Path(conf_dir).mkdir(parents=True, exist_ok=True) if name == "save": file_name, _ = QFileDialog.getSaveFileName( self, "Save Cam Control configuration", conf_dir, "Cam Control Conf (*.ccconf)") if file_name: if not file_name.endswith(".ccconf"): file_name += ".ccconf" with open(file_name, "w") as fd: json.dump(self.camCtr.ctrls, fd) else: file_name, _ = QFileDialog.getOpenFileName( self, "Load Cam Control configuration", conf_dir, "Cam Control Conf (*.ccconf)") if file_name: with open(file_name, "r") as fd: self.camCtr.ctrls = json.load(fd) self.camCtr.update() self.sync()
def getSaveFileName(self, name, parent=None, caption='', dir_='', filter_='', selectedFilter='', options=QFileDialog.Options()): ''' @param: name QString @param: parent QWidget @param: caption QString @param: dir_ QString @param: filter_ QString @param: selectedFilter QString TODO: this is an output parameter @param: options QFileDialog::Options @return: QString ''' settings = Settings() settings.beginGroup('FileDialogPaths') lastDir = settings.value(name, '') fileName = self.getFileName(dir_) if not lastDir: lastDir = dir_ else: lastDir = pathjoin(lastDir, fileName) path, selectedFilter = QFileDialog.getSaveFileName(parent, caption, lastDir, filter_, selectedFilter, options) if path: settings.setValue(name, QFileInfo(path).absolutePath()) settings.endGroup() return path
def buttonOpenClicked(self): fileDialog = QFileDialog( self, "打开历史数据文件", QApplication.applicationDirPath() + "/../data", "Database File (*.db *.mdb)" ) if fileDialog.exec_() == QDialog.Rejected: return # clear curve self.curveHistory.clear() # filePaths = fileDialog.selectedFiles() if filePaths.isEmpty(): return filePath = filePaths.first() if filePath.isEmpty(): return # open database if not DatabaseMgr().open(filePath): return # startTime = QDateTime.fromMSecsSinceEpoch(DatabaseMgr().startTime()) endTime = QDateTime.fromMSecsSinceEpoch(DatabaseMgr().endTime()) self.dateTimeEditStart.setDateTimeRange(startTime, endTime) self.dateTimeEditEnd.setDateTimeRange(startTime, endTime) self.dateTimeEditEnd.setDateTime(endTime) self.dateTimeEditStart.setDateTime(startTime) # title of curve self.curveHistory.setTitle("历史数据回放" + "(" + QFileInfo(filePath).fileName() + ")")
def change_homescreen(): dialog = QFileDialog(self, _("Choose Homescreen")) filename, __ = dialog.getOpenFileName() if not filename: return # user cancelled if filename.endswith('.toif'): img = open(filename, 'rb').read() if img[:8] != b'TOIf\x90\x00\x90\x00': handler.show_error('File is not a TOIF file with size of \ 144x144') return else: from PIL import Image # FIXME im = Image.open(filename) if im.size != (128, 64): handler.show_error('Image must be 128 x 64 pixels') return im = im.convert('1') pix = im.load() img = bytearray(1024) for j in range(64): for i in range(128): if pix[i, j]: o = (i + j * 128) img[o // 8] |= (1 << (7 - o % 8)) img = bytes(img) invoke_client('change_homescreen', img)
def set_path_action_handler(self): file_dialog = QFileDialog() path = file_dialog.getExistingDirectory( self, "Select directory", "/home/", QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) self.logger.info("Path set to %s", path) self.set_path(path) self.app.save_setting("path", path)
def browse_sample_xray(self): """Browse for a sample xray file to use during x-ray creation""" file_dialog = QFileDialog(self) sample_file = file_dialog.getOpenFileName(caption='Choose sample x-ray to use:', filter='X-Ray or JSON (*.asc *.json)')[0] self.book.sample_xray = sample_file self._sample_xray_edit.setText(sample_file) if sample_file: self.update_aliases_from_file()
def __init__(self, *args): QFileDialog.__init__(self, *args) self.setOption(self.DontUseNativeDialog, True) self.setFileMode(self.ExistingFiles) btns = self.findChildren(QPushButton) self.openBtn = [x for x in btns if 'open' in str(x.text()).lower()][0] self.openBtn.clicked.disconnect() self.openBtn.clicked.connect(self.openClicked) self.selectedFiles = [] self.tree = self.findChild(QTreeView)
def saveFile(self): tab = self.tabWidget.widget(self.tabWidget.currentIndex()) items = tab.children() dialog = QFileDialog.Options() dialog = QFileDialog.DontUseNativeDialog file = QFileDialog.getSaveFileName(items[3], "Save file windows title", "default.txt", " All Files (*)", options=dialog)
def loadMNConf(self): options = QFileDialog.Options() fileName, _ = QFileDialog.getOpenFileName(self, 'Open masternode.conf', 'masternode.conf', 'Text Files (*.conf)', options=options) if fileName: self.mainWindow.loadMNConf(fileName)
def _open_file(self, filter): caption = 'open File' filters = 'File (%s)' % (filter) dlg = QFileDialog(self, caption, self.lastOpenDirPath, filters) dlg.setDefaultSuffix(filter) dlg.setFileMode(QFileDialog.AnyFile) dlg.setOption(QFileDialog.DontUseNativeDialog, False) if dlg.exec_(): return dlg.selectedFiles()[0] return ''
def browse_sample_xray(self): """Browse for a sample xray file to use during x-ray creation""" file_dialog = QFileDialog(self) sample_file = file_dialog.getOpenFileName( caption='Choose sample x-ray to use:', filter='X-Ray or JSON (*.asc *.json)')[0] self.book.sample_xray = sample_file self._sample_xray_edit.setText(sample_file) if sample_file: self.update_aliases_from_file()
def Browse(self): options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog fileName, _ = QFileDialog.getOpenFileName( self, "QFileDialog.getOpenFileName()", "", "All Files (*);;Python Files (*.py)", options=options) if fileName: print(fileName)
def save_file_dialog(parent, filters): dlg = QFileDialog() options = dlg.Options() options |= dlg.DontUseNativeDialog filename, _ = dlg.getSaveFileName(parent, None, "Save model", filter=filters, options=options) if filename == "": return None return filename
def SelectFile(self): file = [] if self.radioButtonDecrypt.isChecked(): file = QFileDialog.getOpenFileName(self, "حدد ملف", "", "*.Haies") else: file = QFileDialog.getOpenFileName(self, "حدد ملف", "", "") self.lineEditSelected.setText(file[0]) if len(self.lineEditSelected.text()) > 0 and os.path.isfile( self.lineEditSelected.text()) and self.lineEditSelected.text( ).split(".")[-1] == 'Haies': self.radioButtonDecrypt.setChecked(True)
def select_exe(self): ''' Create a dialog to select the Prince executable ''' dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) filename = dialog.getOpenFileName(self, _('Select Prince executable'), '', '') if filename: try: self.exe.setText(filename) except(TypeError): self.exe.setText(filename[0])
def openFileDlg(self): """Open file picker for ppscannos.py file""" d = self.lineEditPPScannos.text() if d: d = os.path.dirname(d) dlg = QFileDialog(self, "Select PPScannos File...", None, "Python Files (*.py);;All Files (*)") dlg.setFileMode(QFileDialog.ExistingFile) if dlg.exec(): flist = dlg.selectedFiles() # returns a list if len(flist): self.lineEditPPScannos.setText(flist[0])
def select_batch_files(self): """ Selection of .xml pyIMD project files for batch calculation. """ filter_ext = "XML (*.xml);;, All files (*.*) " file_name = QFileDialog() file_name.setFileMode(QFileDialog.ExistingFiles) ret = file_name.getOpenFileNames( self, "Select the pyIMD project files for batch processing", self.last_selected_path, filter_ext) files = ret[0] for i in range(0, len(files)): self.batchFileListWidget.addItem(str(files[i]))
def select_exe(self): ''' Create a dialog to select the Prince executable ''' dialog = QFileDialog() dialog.setFileMode(QFileDialog.ExistingFile) filename = dialog.getOpenFileName(self, _('Select Prince executable'), '', '') if filename: try: self.exe.setText(filename) except (TypeError): self.exe.setText(filename[0])
def getFile(self): dialg = QFileDialog() dialg.setFileMode(QFileDialog.AnyFile) dialg.setNameFilter("CSV Files (*.csv)") if dialg.exec_(): fileName = dialg.selectedFiles() f = open(fileName[0], 'r') ml = machineLearning(f) with open(fileName[0], 'r') as f: data = f.read() self.textEditor.setPlainText(data) self.table.setRowCount(len(ml)) self.table.setColumnCount(1) x = -1 while x <= len(ml) - 2: x += 1 self.table.setItem(x, 0, QTableWidgetItem(ml[x])) header = self.table.horizontalHeader() header.setSectionResizeMode(0, QtWidgets.QHeaderView.Stretch) f.close() else: pass
def video2images_set_export_folder(self): """ Set export folder for the video frames. :return: Nothing """ file_dialog = QFileDialog() f_path = file_dialog.getExistingDirectory(parent=None, caption="Open Directory", directory=QDir.homePath(), options=self.DIALOG_FLAG | QFileDialog.ShowDirsOnly) # print(f_path) if f_path: self.ui_video2images.line_edit_export_images_at.setText(f_path) self.ui_video2images.button_compute.setEnabled(self.UP)
def lataa_tallennettu_rakenne(self): '''Metodi avaa QFileDialog ikkunan, josta käyttäjä valitsee tiedoston, jossa aiemmin tallennettu rakenne sijaitsee. Vain .txt -tiedostot ovat ladattavissa ''' options = QFileDialog.Options() options |= QFileDialog.DontUseNativeDialog tiedosto, _ = QFileDialog.getOpenFileName(self, "Valitse tiedosto", "", "txt Files (*.txt)", options=options) lataus = Lataaja.lataaja(self, tiedosto) if lataus == False: return if lataus == True: self.uusi_rakenne() Lataaja.lataaja(self, tiedosto) tuen_tyyppi = Ominaisuudet.palauta_tuen_tyyppi(self) '''Jos tuki on seinästä, piirretään sitä vastaava grafiikka''' if tuen_tyyppi == 0: self.nayta_seina_tuki() self.gradient_seina_tuki() '''Jos tuki on alhaalta, piirretään sitä vastaava grafiikka''' if tuen_tyyppi == 1: self.nayta_tuki_alhaalta() self.gradient_alatuki() if tuen_tyyppi != 2: self.vaihda_tuki.show() self.lisaa_tuki.hide() '''Jos ulkoinen voima on asetettu, piirretään se''' ulkoinen_voima = int( Ominaisuudet.onko_ulkoinen_voima_asetettu(self)) if ulkoinen_voima == 1: self.nayta_ulkoinen_voima() self.nayta_palkki() Laskin.laskin(self) self.paivita_tulos_teksti() self.tulos.show() self.sp.setValue(float(Ominaisuudet.palauta_palkin_pituus(self))) self.uusiAction.setEnabled(True) self.simuloi.setEnabled(True) '''Kerrotaan käyttäjälle, että kaikki onnistui''' msgBox = QMessageBox() msgBox.setText("Lataus onnistui!") msgBox.setWindowTitle("Onnistunut lataus") msgBox.addButton(QPushButton('OK'), QMessageBox.NoRole) msgBox.exec_()
def save_img_path(self): """ Open the dialog and take the path. :return: True/False, path_string/empty_string """ file_dialog = QFileDialog() f_path = file_dialog.getSaveFileName(parent=None, caption="Save Image as", directory=QDir.homePath(), filter=self.IMG_FILTER, initialFilter="", options=self.DIALOG_FLAG)[0] if f_path: return True, f_path return False, ""
def get_filename_for_save(self): # pragma: no cover filedialog = QFileDialog(self) filedialog.setOption(QFileDialog.DontUseNativeDialog) filedialog.setAcceptMode(QFileDialog.AcceptSave) filedialog.setDirectory( self._parent.cfg.get("TextEditor/LastPath", ".", system=True)) if filedialog.exec_(): self._file_path = filedialog.selectedFiles()[0] self._parent.cfg["SYSTEM", "TextEditor/LastPath"] = (os.path.dirname( self._file_path)) return True return False
def onImportFile(self): '''Import a file which contains a graph and build or rebuild the model with this graph.''' # Load graph from file with pydot_ng result = QFileDialog.getOpenFileName(None, "Import", None, MainWindowController.dotFilter) # Check if Open button has been pressed if len(result[0]) > 0: # Load dot file into a pydot graph # pydotGraph = graph_from_dot_file(result[0]) # Clear graph (ask to save before importing here in a future # extension) self.onClearGraph() # Nodes and edges are send to the model in importGraph() in TextGraphView # If importGraph() is clean or change you could remove comments of theses # lines to build the model # # Create nodes from pydot nodes # for node in pydotGraph.get_nodes(): # self.model.addNode(node.get_name(), node.get_attributes()) # # # Create edges from pydot edges # for edge in pydotGraph.get_edges(): # self.model.addEdge(edge.get_source(), edge.get_destination()) # Send graph's textual representation to the textual controller with open(result[0], "r") as file: self.textGraphController.importGraph(file.read())
def _saveImage(self): filename = QFileDialog.getSaveFileName( self, "Save FITS file", self._save_dir, "FITS files(*.fits *.FITS *fts *FTS)", options=QFileDialog.DontUseNativeDialog) filename = str(filename[0]) if not filename: return busy = BusyIndicator() self._imgman.signalShowMessage.emit( """Writing FITS image %s""" % filename, 3000) QApplication.flush() try: self.image.save(filename) except Exception as exc: busy.reset_cursor() traceback.print_exc() self._imgman.signalShowErrorMessage.emit( """Error writing FITS image %s: %s""" % (filename, str(sys.exc_info()[1]))) return None self.renderControl().startSavingConfig(filename) self.setName(self.image.name) self._qa_save.setVisible(False) self._wsave.hide() busy.reset_cursor()
def save_packets(self): file_path,type = QFileDialog.getSaveFileName(self, "save file", "","Text Files (*.txt)") saved_file = open(file_path+".txt", 'a') for packet in self.pac_list: if packet.tcp: saved_file.write(toAscii(bytes.hex(packet.tcp.actual_data))) saved_file.close()
def change_dir(self): dlg = str(QFileDialog.getExistingDirectory(self, "Select Directory")) if dlg != "": self.settings.edit('save_dir', dlg) self.txt_default_dir.setText(dlg) SETTINGS.settings_list['save_dir'] = dlg
def save_game(self): path = QFileDialog.getSaveFileName(self, 'Create save file', QDir.currentPath() + '/sav')[0] if path != '': save(path, self.play_widget.game, self.play_widget.export_log(), self.play_widget.move_count) self.statusbar.showMessage('Game saved', 5000)
def saveXML(self): if len(self.tools.framemenu.getAllFrames()) > 1: result = QFileDialog.getSaveFileName(self, 'Choose the destination for the animation file!', '.', 'Animation File (*.armo)') if result[0] != "": XML().toXML(self.tools.framemenu.getAllFrames(), result[0]) else: QMessageBox.information(self, "Stickman Message", "You need at least 2 frames to save the animation!")
def edit_kobo_directory(self): tmpkobodirectory = QFileDialog.getExistingDirectory( self, "Select Kobo directory", self.kobodirectory or "/home", QFileDialog.Option.ShowDirsOnly) if tmpkobodirectory != u"" and tmpkobodirectory is not None: self.kobodirectory = tmpkobodirectory
def _open_dir(self): dir_path = QFileDialog.getExistingDirectory(self, 'Open Directory', self.lastOpenDirPath, QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks) self.lastOpenDirPath = dir_path return dir_path
def linked(self): filter = "CSV (*.csv)" fileName = QFileDialog.getSaveFileName(self, "Save Image", filter=filter) if fileName[0]: self.save(fileName[0])
def button_xhtml_filename_handler(self): initial_dir = os.path.dirname(str(self.xhtml_filename.text())) new_file = QFileDialog.getOpenFileName(self, "Select ex libris XHTML file", initial_dir, "XHTML Files (*.xhtml)") if new_file: new_file = new_file[0] if isinstance(new_file, tuple) else new_file if new_file and os.path.exists(new_file): self.xhtml_filename.setText(new_file)
def save(self): path, t = QFileDialog.getSaveFileName() cur = self.document.begin() last = self.document.end() with open(path, 'w') as f: while cur != last: f.write(cur.text()+'\n\n') cur = cur.next()
def fileSaveAs(self): fn, _ = QFileDialog.getSaveFileName(self, "Save as...", None, "text files (*.txt);;All Files (*)") if not fn: return False self.setCurrentFileName(fn) return self.fileSave()
def exportFileCSVData(self): if self.slotsExportedDisabled_: return util = FLUtil() fileName = QFileDialog.getSaveFileName( self, util.translate("app", "Exportar a CSV"), "", util.translate("app", "Fichero CSV (*.csv *.txt)") ) if not fileName or fileName == "": return if not fileName.upper().contains(".CSV"): fileName = fileName + ".csv" q = QtCore.QMessageBox.question( self, util.translate("app", "Sobreescribir {}").format(fileName), util.translate( self, "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate("app", "&Sí"), util.translate("app", "&No"), "", 0, 1 ) if QtCore.QFile.exists(fileName) and q: return file = QtCore.QFile(fileName) if file.open(Qt.IO_WriteOnly): stream = QtCore.QTextStream(file) stream << self.csvData() << "\n" file.close() else: QtCore.QMessageBox.critical( self, util.translate("app", "Error abriendo fichero"), util.translate( "app", "No se pudo abrir el fichero {} para escribir: {}" ).format( fileName, QtWidgets.QApplication.translate( "QFile", file.errorString() ) ) )
def fromXML(self): file = QFileDialog.getOpenFileName(self, "Load Animation", ".", "Animation Files (*.armo)") if file[0] != "": try: frames = XML().fromXML(file[0]) self.tools.framemenu.removeAllFrames() for frame in frames: self.tools.framemenu.addNewFrame(frame) if len(frames) > 0: getWorld().setWorldFrom(frames[0]) except: QMessageBox.information(self, "Stickman Message", "The animation file is not valid!")
def onAddPage(self, chapter): print ('onAddPage') filename = QFileDialog.getOpenFileName(self, caption='Choisir le contenu de la page', directory=Config().instance.settings.path_to_book()) if filename : if chapter.content != None: chapitre = chapter.getParent() else: chapitre = chapter print ('chapitre partnt',chapitre.title) test = Chapitre(chapitre, "undefined", os.path.basename(filename[0])) chapitre.addChild(test) self.model.print_() self.reload()
def fileSearch(self): use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ filterString = 'wordconv.exe (wordconv.exe)' with SanitizeLibraryPath(): opts = QFileDialog.Option() if not use_native_dialog: opts |= QFileDialog.DontUseNativeDialog selectedFile = QFileDialog.getOpenFileName(parent=self, caption=_('Find wordconv.exe'),directory = self.opt_wordconv_exe_path.text(),filter = filterString,options=opts) if selectedFile: selectedFile = selectedFile[0] if isinstance(selectedFile, tuple) else selectedFile if selectedFile and os.path.exists(selectedFile): self.opt_wordconv_exe_path.setText(selectedFile)
def buttonExportClicked(self): (filePaths, filter) = QFileDialog.getOpenFileNames( parent=self, caption="转换数据库文件为文本格式", directory=QApplication.applicationDirPath() + "/../data", filter="Database file (*.db * mdb)", ) if not filePaths: return # if DatabaseMgr().convertToText(filePaths): QMessageBox.information(self, "格式转换", "转换成功!") else: QMessageBox.warning(self, "格式转换", "转换失败!")
def onSaveFile(self): '''Save in a file the text description of the graph.''' # Export dialog result = QFileDialog.getSaveFileName(None, "Export", None, MainWindowController.dotFilter) # Check if Save button has been pressed if len(result[0]) > 0: filePath = result[0] # Create file dotFile = QFile(filePath) if (not dotFile.open(QIODevice.WriteOnly | QIODevice.Text)): QMessageBox.warning(None, "Export", "Export failed.") else: # Write the text from the TextGraphView into the file dotFile.write(QByteArray(self.textGraphController.view .getText().encode("utf_8"))) dotFile.close()
def exportToPDF(self): if self.slotsExportedDisabled_: return util = FLUtil() fileName = QFileDialog.getSaveFileName( self, util.translate("app", "Exportar a PDF"), "", util.translate("app", "Fichero PDF (*.pdf)") ) if fileName[0] == '': return if fileName[0].upper().find(".PDF") == -1: fileName = fileName[0] + ".pdf" if QtCore.QFile.exists(fileName): q = QMessageBox.question( self, util.translate("app", "Sobreescribir {}").format(fileName), util.translate( "app", "Ya existe un fichero llamado {}. ¿Desea sobreescribirlo?" ).format(fileName), util.translate("app", "&Sí"), util.translate("app", "&No"), "", 0, 1 ) if q: return self.slotPrintReportToPdf(fileName)
def __init__(self, title=_('Choose Files'), filters=[], add_all_files_filter=True, parent=None, modal=True, name='', mode=QFileDialog.ExistingFiles, default_dir=u'~', no_save_dir=False, combine_file_and_saved_dir=False ): QObject.__init__(self) ftext = '' if filters: for filter in filters: text, extensions = filter extensions = ['*'+(i if i.startswith('.') else '.'+i) for i in extensions] ftext += '%s (%s);;'%(text, ' '.join(extensions)) if add_all_files_filter or not ftext: ftext += 'All files (*)' if ftext.endswith(';;'): ftext = ftext[:-2] self.dialog_name = name if name else 'dialog_' + title self.selected_files = None self.fd = None if combine_file_and_saved_dir: bn = os.path.basename(default_dir) prev = dynamic.get(self.dialog_name, expanduser(u'~')) if os.path.exists(prev): if os.path.isfile(prev): prev = os.path.dirname(prev) else: prev = expanduser(u'~') initial_dir = os.path.join(prev, bn) elif no_save_dir: initial_dir = expanduser(default_dir) else: initial_dir = dynamic.get(self.dialog_name, expanduser(default_dir)) if not isinstance(initial_dir, basestring): initial_dir = expanduser(default_dir) if not initial_dir or (not os.path.exists(initial_dir) and not ( mode == QFileDialog.AnyFile and (no_save_dir or combine_file_and_saved_dir))): initial_dir = select_initial_dir(initial_dir) self.selected_files = [] use_native_dialog = 'CALIBRE_NO_NATIVE_FILEDIALOGS' not in os.environ with sanitize_env_vars(): opts = QFileDialog.Option() if not use_native_dialog: opts |= QFileDialog.DontUseNativeDialog if mode == QFileDialog.AnyFile: f = QFileDialog.getSaveFileName(parent, title, initial_dir, ftext, "", opts) if f and f[0]: self.selected_files.append(f[0]) elif mode == QFileDialog.ExistingFile: f = QFileDialog.getOpenFileName(parent, title, initial_dir, ftext, "", opts) if f and f[0] and os.path.exists(f[0]): self.selected_files.append(f[0]) elif mode == QFileDialog.ExistingFiles: fs = QFileDialog.getOpenFileNames(parent, title, initial_dir, ftext, "", opts) if fs and fs[0]: for f in fs[0]: f = unicode(f) if not f: continue if not os.path.exists(f): # QFileDialog for some reason quotes spaces # on linux if there is more than one space in a row f = unquote(f) if f and os.path.exists(f): self.selected_files.append(f) else: if mode == QFileDialog.Directory: opts |= QFileDialog.ShowDirsOnly f = unicode(QFileDialog.getExistingDirectory(parent, title, initial_dir, opts)) if os.path.exists(f): self.selected_files.append(f) if self.selected_files: self.selected_files = [unicode(q) for q in self.selected_files] saved_loc = self.selected_files[0] if os.path.isfile(saved_loc): saved_loc = os.path.dirname(saved_loc) if not no_save_dir: dynamic[self.dialog_name] = saved_loc self.accepted = bool(self.selected_files)
def open_file_dialog(self): file_dialog = QFileDialog() self.file_path_tview.setText(QFileDialog.getOpenFileName(file_dialog, str("Choose a SCIM Table"), "", str("Scim Tables (*.in *.txt)"))[0])
def sig_export(self): path = QFileDialog.getSaveFileName(caption="Save", filter="Markdown (*.md);;Text (*.txt);;HTML (*.html *.htm);;All (*)") print(path)
def load(self): path, t = QFileDialog.getOpenFileName() markdown = Markdown() markdown.serializer = self._loader markdown.convertFile(path)
def onEmpireChanged (self): filename = QFileDialog.getExistingDirectory(self, caption='Empire ? ', directory=Config().instance.path_to_pic()) if filename != None: self.lineEditEmpire.setText(os.path.basename(filename))
def sig_import(self): path = QFileDialog.getOpenFileName() self.controller.handle_load(path) self.win_editor.setDocument(self.win_editor.document())
def _import_keys(self): dialog = QFileDialog() dialog.setFileMode(QFileDialog.Directory) dialog.setOption(QFileDialog.ShowDirsOnly) folder = dialog.getExistingDirectory(caption="Select Directory") self._km.import_keys(folder)
def findBackground(self): file = QFileDialog.getOpenFileName(self, "Open Image", ".", "Image Files (*.png *.jpg)") if file[0] != "": getWorld().setBackground(file[0])
def fileOpen(self): fn, _ = QFileDialog.getOpenFileName(self, 'Open File...', None, 'Text Files (*.txt);;All Files (*)') if fn: self.loadSrc(fn) self.loadLog(None) # clears logPane, logBox title, etc
def onGroupeChanged (self): filename = QFileDialog.getExistingDirectory(self, caption='', directory=self.path) if filename != None: self.lineEditGroupe.setText(os.path.basename(filename))