def save_model_fn(self): """ save the current mesh settings to a file """ fn_dialog = QtWidgets.QFileDialog() save_fn = str( fn_dialog.getSaveFileName(caption='Choose ModEM model file', filter='*.rho')) sv_path = os.path.dirname(save_fn) sv_basename = os.path.basename(save_fn) self.model_widget.model_obj.write_model_file( save_path=sv_path, model_fn_basename=sv_basename)
def exportFileDialog(self, window_title, name_filter, default_suffix): """ Show file export dialog """ dialog = QtWidgets.QFileDialog() dialog.setWindowTitle(window_title) dialog.setNameFilter(name_filter) dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setDefaultSuffix(default_suffix) if dialog.exec_() == QtWidgets.QDialog.Accepted: return str(dialog.selectedFiles()[0]) return None
def GetIRTInputFile(self): file = QtWidgets.QFileDialog() file.setFileMode(QtWidgets.QFileDialog.ExistingFile) possibleinputFile,_ = QtWidgets. QFileDialog.getOpenFileName(UI_MainWindow.Ui_MainWindow.tab, "Browse", "", "TraML Files (*.TraML)", options= QtWidgets.QFileDialog.\ Options()) if possibleinputFile: if possibleinputFile.endswith( '.TraML') or possibleinputFile.endswith( '.tsv') or possibleinputFile.endswith('.csv'): return possibleinputFile
def load_eqs(self): """Загрузка из файла""" try: self.reset() name = QtWidgets.QFileDialog().getOpenFileName( self.widget, 'Load equations', '', 'Equations (*.eqs)') if name[0]: with open(name[0], 'rb') as f: self.eqs = pickle.load(f) for eq in self.eqs: self.Eqlist.addItem(QtWidgets.QListWidgetItem(eq)) self.update_roots() except Exception as f: self.widget.show_exeption(f)
def chooseButtonClicked(self): #fname = QtWidgets.QFileDialog.getOpenFileName(self, #'Choose application', #'', #QDir.Executable)[0] # this doesn't work diag = QtWidgets.QFileDialog() diag.setFilter(QDir.Executable) fname = diag.exec_() self.le.setText(fname) return
def saveAsFile(self): """Save the file with the name chosen by the user in the folder chose in the file explorer of the computer""" try: if self.name[0][:8] == "untitled": os.remove(self.name[0]) except Exception: pass try: repository = QtWidgets.QFileDialog() self.name = repository.getSaveFileName() self.saveFile() except Exception as error: print(error)
def on_action_save_image_triggered(self): img_formats = ' '.join(['*' + img for img in IMAGE_FILE_FORMATS]) if self.model.comic: path = self.model.current_directory + \ self.model.get_current_page_title() file_path = QtWidgets.QFileDialog().getSaveFileName( self, self.tr('Save Current Page'), path, self.tr('images (%s)' % (img_formats))) if file_path: logger.info('Saving image') self.model.save_current_page_image(file_path[0])
def getOpenFilesAndDirs(parent=None, caption='', directory='', filter='', initialFilter='', options=None): """ This function not coded by me. Source: https://stackoverflow.com/questions/64336575/select-a-file-or-a-folder-in-qfiledialog-pyqt5 """ def updateText(): # update the contents of the line edit widget with the selected files selected = [] for index in view.selectionModel().selectedRows(): selected.append('"{}"'.format(index.data())) lineEdit.setText(' '.join(selected)) dialog = QtWidgets.QFileDialog(parent, windowTitle=caption) dialog.setFileMode(dialog.ExistingFiles) if options: dialog.setOptions(options) dialog.setOption(dialog.DontUseNativeDialog, True) if directory: dialog.setDirectory(directory) if filter: dialog.setNameFilter(filter) if initialFilter: dialog.selectNameFilter(initialFilter) # by default, if a directory is opened in file listing mode, # QFileDialog.accept() shows the contents of that directory, but we # need to be able to "open" directories as we can do with files, so we # just override accept() with the default QDialog implementation which # will just return exec_() dialog.accept = lambda: QtWidgets.QDialog.accept(dialog) # there are many item views in a non-native dialog, but the ones displaying # the actual contents are created inside a QStackedWidget; they are a # QTreeView and a QListView, and the tree is only used when the # viewMode is set to QFileDialog.Details, which is not this case stackedWidget = dialog.findChild(QtWidgets.QStackedWidget) view = stackedWidget.findChild(QtWidgets.QListView) view.selectionModel().selectionChanged.connect(updateText) lineEdit = dialog.findChild(QtWidgets.QLineEdit) # clear the line edit contents whenever the current directory changes dialog.directoryEntered.connect(lambda: lineEdit.setText('')) dialog.exec_() return dialog.selectedFiles()
def addConfigFromFile(self) -> None: ''' Callback when a config file is double clicked in the file browser Place the selected file name in the browsing drop-down menu, the call the self.loadConfig callback of the load button. ''' filepath = QtWidgets.QFileDialog(directory=self.defaultParPath).getOpenFileName( self, "Select parameter file", "", "parameters file (*.py);;hdf5 file (*.h5);;all files (*)") self.uiBase.wao_selectConfig.clear() self.uiBase.wao_selectConfig.addItem(str(filepath[0])) self.loadConfig()
def saveOutput(self): fileDialog = QtWidgets.QFileDialog(self.centralwidget) fileDialog.setDirectory('../MAST-U_output/g' + self.efitFile.rsplit('.')[0]) directory = fileDialog.getExistingDirectory() fileDialog.destroy() if directory == '': return src_files = os.listdir('../MAST-U_output/temp') for file_name in src_files: full_file_name = os.path.join('../MAST-U_output/temp', file_name) if (os.path.isfile(full_file_name)): shutil.copy(full_file_name, directory) print(len(src_files), 'orbit output files were coppied to ', directory)
def selectfile(self): # dialog = myQtW.QFileDialog(self) # dialog.exec_() # self.open_and_read(self.inputfile.text()) dialog = myQtW.QFileDialog(self) directory = os.getcwd() #myQtW.QFileDialog.getExistingDirectory(self) dialog.setDirectory(directory) # self.inputfile.text() ) if QtCore.QDir(self.inputfile.text()).exists(): dialog.selectFile(self.inputfile.text()) if dialog.exec_(): self.inputfile.setText(dialog.selectedFiles()[0]) self.open_and_read(self.inputfile.text())
def openFile(self): """Open the file selected in the file explorer of the computer""" try: repository = QtWidgets.QFileDialog() self.name = repository.getOpenFileName() points, taxiways, runways = [], [], [] origin = QtCore.QPointF(0, 0) factor = (1, 1, 1) path = self.name[0] file = open(path, 'r') airport_name = file.readline().split()[0] lines = file.readlines() for line in lines: words = line.strip().split() name = words[1] try: if words[0] == 'I': # Image description self.image_repository = words[1] self.image_signal.ask_image_signal.emit( self.image_repository) if words[0] == 'O': # Origin and scale factor description xy_str = words[1].split(',') x, y = float(xy_str[0]), float(xy_str[1]) origin = QtCore.QPointF(x, y) factor = (float(words[2]), float(words[3]), float(words[4])) if words[0] == 'P': # Point description pt_type = point_types[int(words[2])] points.append( airport.NamedPoint(name, pt_type, words[3])) elif words[0] == 'L': # Taxiway description speed = int(words[2]) cat = categories[words[3]] one_way = words[4] == 'S' xys = xys_to_points(words[5:]) taxiways.append( airport.Taxiway(name, speed, cat, one_way, xys)) elif words[0] == 'R': # Runway description pts = tuple(words[4].split(',')) xys = xys_to_points(words[5:]) runways.append( airport.Runway(name, words[2], words[3], xys, pts)) except Exception as error: print(error, line) file.close() self.airport = airport.Airport(airport_name, points, taxiways, runways, origin, factor) except Exception: pass
def get_file_name(self, action): logging.debug('utilities.py - get_file_name - action ' + str(action)) file_dialog = QtWidgets.QFileDialog() filter_types = 'XML Files (*.xml)' out_file_name = None if action == 'save': # noinspection PyArgumentList out_file_name, _ = file_dialog.getSaveFileName(self, 'Save File', '', filter_types) elif action == 'open': # noinspection PyArgumentList out_file_name, _ = file_dialog.getOpenFileName(self, 'Open File', '', filter_types) return str(out_file_name)
def change_path(self): file_dialog = QtWidgets.QFileDialog() fpath, _ = file_dialog.getOpenFileName( filter="csv (*.csv)", directory=str(self.cpath.parent) if self.cpath else "") if fpath: self.cpath = Path(fpath) self.path_label.setText("Current path: " + str(self.cpath)) self.settings.setValue("paths/csv", str(self.cpath)) self.settings.sync() self.cs_submit.setEnabled(True) else: if not self.cpath: self.cs_submit.setEnabled(False)
def _callbackPythonButton(self): """ Open dialog and write script. """ dialog = QtWidgets.QFileDialog() dialog.setWindowTitle('Write Python Script') dialog.setNameFilter('Python Files (*.py)') dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog) if dialog.exec_() == QtWidgets.QDialog.Accepted: filename = str(dialog.selectedFiles()[0]) self.write.emit(filename)
def _callbackPDFButton(self): """ Write a PDF file of figure. """ dialog = QtWidgets.QFileDialog() dialog.setWindowTitle('Write *.pdf of figure') dialog.setNameFilter('PDF files (*.pdf)') dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) dialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) dialog.setOption(QtWidgets.QFileDialog.DontUseNativeDialog) if dialog.exec_() == QtWidgets.QDialog.Accepted: filename = str(dialog.selectedFiles()[0]) self.write.emit(filename)
def select_file(line_e_input, label_preview, line_e_current_page, line_e_last_page): file = QtWidgets.QFileDialog.getOpenFileName(QtWidgets.QFileDialog(), 'Select Pdf', '', 'pdf (*.pdf)') path = file[0] if is_valid_path(path): line_e_input.setText(path) load_preview(path, 0, label_preview, line_e_current_page, line_e_last_page) else: line_e_input.setText('')
def action_export(self): global SuffixList # 获取当前选择的内容 self.getSelected.emit() length = len(self.SelectedModelList) if length == 0: pass # 选择本地路径 if length == 1: # 对于单文件 _translate = QtCore.QCoreApplication.translate FileDialog = QtWidgets.QFileDialog( self, _translate("FileDialog", "Export 3D model files")) FileDialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) FileDialog.setViewMode(QtWidgets.QFileDialog.Detail) FileDialog.setFileMode(QtWidgets.QFileDialog.AnyFile) FileDialog.setNameFilters(SuffixList) FileDialog.setLabelText(FileDialog.Accept, _translate("FileDialog", "&Export")) if FileDialog.exec() == QtWidgets.QFileDialog.Accepted: FilepathList = FileDialog.selectedFiles() else: return else: # 对于多个文件 _translate = QtCore.QCoreApplication.translate FileDialog = QtWidgets.QFileDialog( self, _translate("FileDialog", "Export 3D model files")) FileDialog.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen) FileDialog.setViewMode(QtWidgets.QFileDialog.Detail) FileDialog.setFileMode(QtWidgets.QFileDialog.DirectoryOnly) FileDialog.setLabelText(FileDialog.Accept, _translate("FileDialog", "&Export")) if FileDialog.exec() == QtWidgets.QFileDialog.Accepted: FilepathList = FileDialog.selectedFiles() else: return
def __init__(self, parent: Optional[QtWidgets.QWidget] = None) -> None: super().__init__(parent) self.setupUi(self) # type: ignore default_output_dir = os.path.realpath( os.path.join(cur_dir, '..', 'output')) self.output_dir.setText(default_output_dir) screen_size = QtWidgets.qApp.primaryScreen().size() self.setGeometry((screen_size.width() - self.width()) / 2, (screen_size.height() - self.height()) / 2, self.width(), self.height()) self.choose_output_dir = QtWidgets.QFileDialog(self) self.choose_output_dir.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen) self.choose_output_dir.setFileMode(QtWidgets.QFileDialog.DirectoryOnly) self.choose_output_dir.setDirectory(default_output_dir) self.browse_dir.clicked.connect(self.choose_output_dir.exec_) self.choose_output_dir.directoryEntered[str].connect( self.output_dir.setText) self.close_gui.clicked.connect(self.close) self.run_script.clicked.connect(self._run) default_excel_file = os.path.realpath( os.path.join(cur_dir, 'Measurement.xlsx')) self.choose_excel_file = QtWidgets.QFileDialog(self) self.choose_excel_file.setAcceptMode(QtWidgets.QFileDialog.AcceptOpen) self.choose_excel_file.setFileMode(QtWidgets.QFileDialog.ExistingFile) self.choose_excel_file.setDirectory( os.path.dirname(default_excel_file)) self.excelFile.setText(default_excel_file) self.browse_excel_file.clicked.connect(self.choose_excel_file.exec_) self.choose_excel_file.fileSelected[str].connect( self.excelFile.setText)
def loadClicked(self): """ The user has selected the "load from from" option. Prompt for a file location and load the wallet. """ app = self.app fd = QtWidgets.QFileDialog(self, "select wallet file") fd.setViewMode(QtWidgets.QFileDialog.Detail) qdir = QtCore.QDir fd.setFilter(qdir.Dirs | qdir.Files | qdir.NoDotAndDotDot | qdir.Hidden) if (fd.exec_()): fileNames = fd.selectedFiles() if len(fileNames) != 1: log.error("More than 1 file selected for importing") raise Exception("More than 1 file selected for importing") else: raise Exception("no file selected") walletPath = fileNames[0] log.debug('loading wallet from %r' % walletPath) if walletPath == "": app.appWindow.showError("no file selected") elif not os.path.isfile(walletPath): log.error("no file found at %s" % walletPath) app.showMessaage("file error. try again") else: def load(pw, userPath): if pw is None or pw == "": app.appWindow.showError( "you must enter the password for this wallet") else: try: appWalletPath = app.walletFilename() wallet = Wallet.openFile(userPath, pw) # Save the wallet to the standard location. wallet.path = appWalletPath wallet.save() app.setWallet(wallet) app.home() except Exception as e: log.warning( "exception encountered while attempting to open wallet: %s" % formatTraceback(e)) app.appWindow.showError( "error opening this wallet? password correct? correct network?" ) app.getPassword(load, walletPath)
def browse2open(self): sender = self.sender() if sender == self.buttonbrowse1: input_id = 1 elif sender == self.buttonbrowse2: input_id = 2 else: raise ValueError('Wrong browser.') self.expected_extension = '.odml' self.accepted_extensions = ['.odml', '.xml'] dlg = Qtw.QFileDialog() dlg.setFileMode(Qtw.QFileDialog.AnyFile) dlg.setAcceptMode(Qtw.QFileDialog.AcceptOpen) dlg.setLabelText(Qtw.QFileDialog.Accept, "Open") dlg.setDefaultSuffix(self.expected_extension.strip('.')) dir = None if self.settings.get_object('inputfilename1'): dir = self.settings.get_object('inputfilename1') elif self.settings.get_object('inputfilename2'): dir = self.settings.get_object('inputfilename2') if dir: dlg.setDirectory(os.path.dirname(dir)) if dlg.exec_(): inputname = str(dlg.selectedFiles()[0]) if ((os.path.splitext(inputname)[1] not in self.accepted_extensions) and (os.path.splitext(inputname)[1] != '')): Qtw.QMessageBox.warning( self, 'Wrong file format', 'The input file format is supposed to be "%s",' ' but you selected "%s"' '' % (self.accepted_extensions, os.path.splitext(inputname)[1])) else: setattr(self, 'inputfilename%i' % input_id, inputname) self.settings.register('inputfilename%i' % input_id, self, useconfig=False) short_filename = shorten_path( getattr(self, 'inputfilename%i' % input_id)) getattr(self, 'inputfile%i' % input_id).setText(short_filename) if self.inputfile1 and self.inputfilename2: self.buttonbrowsesave.setEnabled(True)
def open_file(): choose = -1 dialog = QtWidgets.QFileDialog() extension = '' if title == 'Open Video': extension = 'Videos (*.mkv *.mp4 *.mpg)' choose = 1 elif title == 'Open Eng Sub': extension = 'SRT (*.srt)' choose = 2 elif title == 'Open Viewed Video': pass else: extension = 'SRT (*.srt)' choose = 3 #dialog.setDefaultSuffix(".srt") fileName, _ = dialog.getOpenFileName(None, title, QDir.homePath(), extension) name = fileName.lower() if choose == 2: # quy ước loại sub sẽ đặt tên ở đuôi !!! if name[len(name) - 7:len(name) - 4] != 'eng': QtWidgets.QMessageBox.information( None, 'WARNING', 'Please choose correctly sub with format *eng.srt') return elif choose == 3: if name[len(name) - 7:len(name) - 4] != 'vie': QtWidgets.QMessageBox.information( None, 'WARNING', 'Please choose correctly sub with format *vie.srt') return if fileName != '': #self.loadSubToScroll() if title == 'Open Video': self.openVid(fileName) elif title == 'Open Eng Sub': self.openEngSub(fileName) else: self.LoadOtherSub(fileName) loaded = True for p in self.loadedPath: if p == '': loaded = False if loaded: with open('history.txt', 'w') as file: file.writelines(','.join(self.loadedPath))
def action_import_event(self, checked): print("file dialog") dlg = QtWidgets.QFileDialog() dlg.setFileMode(QtWidgets.QFileDialog.AnyFile) dlg.setNameFilters([ "motion files (*.htr)", "motion files (*.bvh)", "all files (*.*)" ]) dlg.setDirectory("C:/Users/mrl/Research/Motions") if dlg.exec_(): file_path = dlg.selectedFiles() ext = os.path.splitext(file_path[0])[1] print("action_import") if ext == ".bvh": joint_motion = bl.read_bvh_file(file_path[0]) elif ext == ".htr": #joint_motion = hl.read_htr_file(file_path[0]) htr_motion = hl.read_htr_file_as_htr(file_path[0]) htr_motion.add_end_effector("L.Foot", mm.seq_to_vec3([100, 0, 0])) joint_motion = htr_motion.to_joint_motion() else: print("invalid file extension") return self.hma.add_motion(joint_motion) self.findChild(mv.MotionView, "motion_view").add_renderer( renderer.JointMotionRender(joint_motion)) mot = self.hma.motion_container[0] ske = mot.get_skeleton() print([n.label for n in ske.get_nodes()]) # foot_index = ske.get_index_by_label("L.Foot") # print(mot.get_position(foot_index, 0)) # print(mot.get_positions(0)) # print(mot.get_velocity(foot_index, 0, 120)) # print(mot.get_velocities(0, 120)) # print(mot.get_acceleration(foot_index, 0, 120)) # print(mot.get_accelerations(0, 120)) # joint_motion = bl.read_bvh_file("../../../../Research/Motions/cmuconvert-daz-01-09/01/01_02.bvh") # joint_motion = bl.read_bvh_file("../../../../Research/Motions/MotionData/Trial001.bvh") # joint_motion = bl.read_bvh_file("../../../../Research/Motions/cmuconvert-max-01-09/01/01_02.bvh", scale = 3) # joint_motion = hl.read_htr_file("../../../../Research/Motions/snuh/디딤자료-서울대(조동철선생님)/디딤LT/D-1/16115/trimmed_walk01.htr", 1) # self.hma.add_motion(joint_motion) # self.findChild(mv.MotionView, "motion_view").add_renderer(renderer.JointMotionRender(joint_motion)) print("import success") """
def new_images(self): logging.info('open new images dialog has been opened') dialog = QtWidgets.QFileDialog() dialog.setFileMode(QtWidgets.QFileDialog.AnyFile) directory = dialog.getOpenFileNames(None, 'select images', __file__, "image files(*.png *.jpg *.jpeg)") fileNames = directory[0] # check that the user choosed 2 images if len(fileNames) != 2: self.warnDialog("please choose 2 images") logging.error("the user has not choosed 2 images") return image_1 = fileNames[0] image_2 = fileNames[1] logging.info('images has been loaded') # check the size of the tw2 images # try : mixer = Mixer(image_1, image_2) logging.info('mixer Object has been started') if not mixer.is_the_same_size(): self.warnDialog("please check that your images have tha same size") logging.critical('user inserted 2 images not having the same size') return # start mixing and displaying the images components self.paths[0] = image_1 self.paths[1] = image_2 logging.info('images has the same size and has been prepared to show') image_arr1 = mpimg.imread(self.paths[0]) image_arr2 = mpimg.imread(self.paths[1]) self.img_arrays = [image_arr1, image_arr2] logging.info('making initial mix') self.mix() logging.info('initial mix Done ...') self.Image1ViewerA.setPixmap( QtGui.QPixmap(image_1).scaled(self.Image1ViewerA.width(), self.Image1ViewerA.height(), QtCore.Qt.IgnoreAspectRatio)) self.Image2ViewerA.setPixmap( QtGui.QPixmap(image_2).scaled(self.Image2ViewerA.width(), self.Image2ViewerA.height(), QtCore.Qt.IgnoreAspectRatio)) #update components self.Update_img_componentV2(0, "img1") self.Update_img_componentV2(0, "img2") # show widgets self.centralwidget.show() #resize labels self.resizeWindow() MainWindow.setGeometry(80, 80, 100, 200)
def process_gui(self, parent, content): """In order to accept multiple input values, we have to create an additional GUI element that allows to choose to either selfsign certificates or use an existing CA cert and key for signing.""" self.parent = parent self.x509gui = X509CloneGui(self.parent) self.file_open_dialog = QtWidgets.QFileDialog(self.x509gui) self.x509gui.ui.x509clone_selfsign.toggled.connect(self.x509gui.toggle_selfsign) self.x509gui.ui.x509clone_casign.toggled.connect(self.x509gui.toggle_casign) self.x509gui.ui.x509clone_load_cacert_button.clicked.connect(self._load_cert_dialog) self.x509gui.ui.x509clone_load_cakey_button.clicked.connect(self._load_private_key_dialog) if self.x509gui.exec_() == 0: # If the plugin GUI is cancelled, just # return without doing anything. return # Decode content because pyOpenSSL fails with bytearrays. content = content.decode() try: original_cert = OpenSSL.crypto.load_certificate(OpenSSL.crypto.FILETYPE_PEM, content) except (OpenSSL.crypto.Error, TypeError) as e: self.error = Exception('Invalid certificate') self.log.error(self.error) self.log.debug(e, exc_info=True) return signature_algo = original_cert.get_signature_algorithm().decode() if self.x509gui.ui.x509clone_selfsign.isChecked(): new_cert, new_key = self._clone(original_cert, True, signature_algo) elif self.x509gui.ui.x509clone_casign.isChecked(): if not self.ca_cert: self.error = Exception('Invalid CA cert') self.log.error(self.error) self.log.debug(self.error, exc_info=True) return if not self.ca_key: self.error = Exception('Invalid CA key') self.log.error(self.error) self.log.debug(self.error, exc_info=True) return new_cert, new_key = self._clone(original_cert, False, signature_algo) new_cert.set_issuer(self.ca_cert.get_issuer()) new_cert.sign(self.ca_key, signature_algo) else: self.error = Exception('No action selected') self.log.error(self.error) self.log.debug(self.error, exc_info=True) return content = OpenSSL.crypto.dump_privatekey(OpenSSL.crypto.FILETYPE_PEM, new_key) content += OpenSSL.crypto.dump_certificate(OpenSSL.crypto.FILETYPE_PEM, new_cert) return content
def save_to_file(self, file=None): if file is None: dialog = QtWidgets.QFileDialog() dialog.setDefaultSuffix("json") dialog.setAcceptMode(1) dialog.exec() if len(dialog.selectedFiles()) > 0: file = dialog.selectedFiles()[0] else: return self.update_lord(self.Lord_Tab.currentIndex()) output = dict() output["AICShortDescription"] = { "German": self.German.toPlainText(), "English": self.English.toPlainText(), "Polish": self.Polish.toPlainText(), "Russian": self.Russian.toPlainText(), "Chinese": self.Chinese.toPlainText(), "Hungarian": self.Hungarian.toPlainText() } output["AICLongDescription"] = { "German": self.German_2.toPlainText(), "English": self.English_2.toPlainText(), "Polish": self.Polish_2.toPlainText(), "Russian": self.Russian_2.toPlainText(), "Chinese": self.Chinese_2.toPlainText(), "Hungarian": self.Hungarian_2.toPlainText() } output["AICharacters"] = list() for lord in self.lords: lord_info = { "Name": lord.Name, "Description": lord.Description, "Personality": lord.Personality, "CustomName": lord.CustomName } if any(lord.Personality[item] is None for item in lord.Personality): continue elif all( lord.Personality[item] == self.blank_lord.Personality[item] for item in lord.Personality): continue else: output["AICharacters"].append(lord_info) json.dump(output, open(file, encoding="utf-8", newline="\n", mode="w"), indent="\t", ensure_ascii=False)
def writeToFile(self): print(self.sender().objectName()) savedialog = QtWidgets.QFileDialog(self) savedialog.setFileMode(savedialog.AnyFile) savedialog.setAcceptMode(QtWidgets.QFileDialog.AcceptSave) filepath: str file: QtCore.QFile if self.sender().objectName( ) == "saveAs_action" or self.filepath == "": self.filepath = savedialog.getSaveFileName( self, "Выбор файла для сохранения", filter='(*.xml)')[0] filepath = self.filepath file = QtCore.QFile(filepath) if not filepath: return if not file.open(QtCore.QIODevice.WriteOnly): QtWidgets.QMessageBox.information(self, "Unable to save file", file.errorString()) return data = self.model.getList() stream = QtCore.QXmlStreamWriter(file) stream.setAutoFormatting(True) stream.writeStartDocument() stream.writeStartElement("table") for el in data: stream.writeStartElement("person") stream.writeCharacters(el) stream.writeEndElement() stream.writeEndElement() stream.writeEndDocument() file.close() fileinfo = QtCore.QFileInfo(filepath) if stream.hasError(): QtWidgets.QMessageBox.information( self, "Unable to write data in %s" % fileinfo.fileName(), "Something was " "wrong") self.setWindowModified(False) self.setWindowTitle("Task1_Var5 " + fileinfo.fileName() + " [*]")
def newMedia(fldbk): #TODO: need to tweak this to allow multiple fields to be selected caller = fldbk.mMediaTable newFile = QtWidgets.QFileDialog(fldbk, "Add recordings.") if dataIndex.root.get("MediaFolder") != None: newFile.setDirectory(dataIndex.root.get("MediaFolder")) else: '''this keeps the finder out of the interior of the application bundle''' filePath = path.dirname(newFile.directory().currentPath()) fileDir = path.split(filePath) if fileDir[1] == 'com.UNTProject.eFieldbook': newFile.setDirectory(dataIndex.homePath) newFile.setFileMode(QtWidgets.QFileDialog.ExistingFile) if newFile.exec_(): newNames = newFile.selectedFiles() newName = newNames[0] if dataIndex.root.get("MediaFolder") == None or dataIndex.root.get( "MediaFolder") != path.dirname(newName): setDefaultDirectory(newName) for item in newNames: sound2play = item newName = path.basename(item) node = dataIndex.root.find('Media[@Filename="%s"]' % newName) '''call from metadata tab, add media elements to the media table''' if node == None: medID, node = updateMediaInfo(item, newName) mManager = MediaManager.MediaManager(dataIndex.fldbk) mManager.renameWindow(newName) mManager.setValues(medID, caller, item) mManager.setComboBoxes() mManager.exec_() else: node = dataIndex.root.find('Media[@Filename="%s"]' % newName) file = node.attrib.get('Filename') speaker = node.attrib.get('Spkr') date = node.attrib.get('Date') fileInfo = file + " [" + speaker + " " + date + "]" msgbox = QtWidgets.QMessageBox() msgbox.setText("File in database.") msgbox.setInformativeText( 'There is already a recording named\n\n%s\n\nin the database. ' 'Media files should have unique names.' % fileInfo) msgbox.setStandardButtons(QtWidgets.QMessageBox.Ok) msgbox.setDefaultButton(QtWidgets.QMessageBox.Ok) msgbox.exec_() return QtMultimedia.QSound.play(sound2play) dataIndex.unsavedEdit = 1 return medID
def browseInput(self): qfd = QtWidgets.QFileDialog(self.MainWindow) if self.last_input_dir: qfd.setDirectory(self.last_input_dir) if self.inputType == 'file': qfd.setWindowTitle('Select file') qfd.setFileMode(QtWidgets.QFileDialog.ExistingFile) else: qfd.setWindowTitle('Select directory') qfd.setFileMode(QtWidgets.QFileDialog.Directory) if qfd.exec_(): fn = qfd.selectedFiles()[0] self.inputEdit.setText(fn) self.last_input_dir = os.path.split(fn)[0] self.initializeTorrent()
def saveFileAs(self): d = QtWidgets.QFileDialog() fileName, filterName = d.getSaveFileName(self, self.context.getText("dialog_save", "title"), "", "*.bmp;;*.gif;;*.png;;*.xpm;;*.jpg") if fileName.split(".")[-1] in ["bmp", "gif", "png", "xpm", "jpg"]: self.context.currentImage().fileName = fileName self.signals.fileNameChanged.emit(self.context.getCurrentImagePos(), os.path.basename(str(fileName))) else: self.context.currentImage().fileName = fileName + filterName[1:] self.signals.fileNameChanged.emit(self.context.getCurrentImagePos(), os.path.basename(str(fileName + filterName[1:]))) self.context.currentImage().save()