def chpicker(dir, filter='*.*', label='ChiantiPy'): '''Select a filename using a Qt gui dialog.''' app=QtGui.QApplication(sys.argv) a=QtGui.QFileDialog() a.setDirectory(dir) a.setFilter(filter) # mylabel=QtCore.QString('some label') # a.setLabelText(mylabel) a.setWindowTitle(label) a.setModal(True) a.exec_() qfilename=a.selectedFiles() return str(qfilename[0])
def load_from_file(self): try: file_dialog = QtGui.QFileDialog() path = file_dialog.getOpenFileName(None, 'OpenFile', self.default_dir, "Frames file (*.frames)") self.logger.log(logging.DEBUG, "Selected file: " + path) thread = FromFileToGuiQueueThread(self.stop_event, FrameFile(path), self.gui_queue) thread.start() thread.join() except: self.logger.log(logging.ERROR, "Load file exception")
def browseFolderButton(self): _path = self._auto_reduce_folder pathQFileDialog = QtGui.QFileDialog(self.parent) folder = str( pathQFileDialog.getExistingDirectory( self, 'Select Template Folder', _path, QtGui.QFileDialog.ShowDirsOnly)) if folder == "": return self._folder = folder self._populate_table()
def openTheoriePDF(self): dlg = QtGui.QFileDialog() dlg.setFileMode(QtGui.QFileDialog.AnyFile) dlg.setDirectory("../../EW_Common/Python/PDF") dlg.setFilter("Files (*.pdf *.txt)") #filename = QtGui.QFileDialog.getOpenFileName() filename = None if dlg.exec_(): filename = dlg.selectedFiles() if (filename): #subprocess.Popen(filename, shell=True) webbrowser.open_new(r'' + str(filename))
def get_data_file(self): """ get the filename from a file dialogue """ fn_dialog = QtGui.QFileDialog() fn = str( fn_dialog.getOpenFileName(caption='Choose ModEM data file', filter='(*.dat);; (*.data)')) self.plot_response.data_fn = fn self.dir_path = os.path.dirname(fn)
def load_edi_files(self): fn_list = QtGui.QFileDialog().getOpenFileNames( caption='Choose EDI Files', filter='*.edi') self.edi_list = [] for fn in fn_list: self.edi_list.append(str(fn)) self.model_obj = modem.Model(edi_list=self.edi_list) self.model_obj.get_station_locations() self.mpl_widget.plot_mesh(self.model_obj)
def get_model_fn(self): """ read in an existing model file """ fn_dialog = QtGui.QFileDialog() fn = str(fn_dialog.getOpenFileName(caption='Choose ModEM model file', filter='*.rho')) self.model_obj = modem.Model() self.model_obj.read_model_file(fn) self.dir_path = os.path.dirname(fn)
def on_open(self): """ Display a dialogue to open a sequence """ # Stop control widget if not self.control_widget.reset(): return # Get the filename filename = unicode(QtGui.QFileDialog().getOpenFileName( self, "Open", ".", "*.xml")) if filename == u"": return return self.open(filename)
def _on_click_btnLoadVector(self): dialog = QtGui.QFileDialog(self) dialog.setFileMode(QtGui.QFileDialog.ExistingFiles) if self._last_opened_folder is not None: dialog.setDirectory(self._last_opened_folder) # dialog.setFileMode(QtGui.QFileDialog.Directory ) filters = [u"국토지리정보 벡터파일(*.gpkg *.shp *.pdf *.dxf)"] dialog.setNameFilters(filters) if (dialog.exec_()): fileList = dialog.selectedFiles() else: return pdfList = list() shpList = list() gpkgList = list() dxfList = list() for vectorPath in fileList: filename, extension = os.path.splitext(vectorPath) if extension.lower() == ".pdf": pdfList.append(vectorPath) elif extension.lower() == ".shp": shpList.append(vectorPath) elif extension.lower() == ".gpkg": gpkgList.append(vectorPath) elif extension.lower() == ".dxf": dxfList.append(vectorPath) # 온맵은 한 파일씩 그룹으로 임포트 if self._onMapLoader: for vectorPath in pdfList: self._onMapLoader.runImport(vectorPath) # Shp의 경우 여러 파일을 하나의 그룹으로 묵어 임포트 if self._shpLoader: self._shpLoader.runImport(shpList) # Gpkg 한 파일씩 그룹으로 임포트 if self._gpkgLoader: for vectorPath in gpkgList: self._gpkgLoader.runImport(vectorPath) # DXF 한 파일씩 그룹으로 임포트 if self._dxfLoader: for vectorPath in dxfList: self._dxfLoader.runImport(vectorPath)
def fileDialog(fdMode='open', fdFileMode='AnyFile', fdRoot=None, fdRoots=None, fdFilters=None, fdCmd=None): """ FileDialog popup :param fdMode: setAcceptMode 'open' or 'save' :type fdMode: str :param fdFileMode: setFileMode 'AnyFile', 'ExistingFile', 'Directory', 'DirectoryOnly' :type fdFileMode: str :param fdRoot: Start root path :type fdRoot: str :param fdRoots: List of recent files (list[str(QUrl)]) :type fdRoots: list :param fdFilters: List of extensions :type fdFilters: list :param fdCmd: Command for accepted execution :type fdCmd: function :return: QFileDialog widget object :rtype: QtGui.QFileDialog """ fd = QtGui.QFileDialog() #--- FileDialog AcceptedMode ---# if fdMode == 'open': fd.setAcceptMode(QtGui.QFileDialog.AcceptOpen) elif fdMode == 'save': fd.setAcceptMode(QtGui.QFileDialog.AcceptSave) #--- FileDialog FileMode ---# if fdFileMode == 'AnyFile': fd.setFileMode(QtGui.QFileDialog.AnyFile) elif fdFileMode == 'ExistingFile': fd.setFileMode(QtGui.QFileDialog.ExistingFile) elif fdFileMode == 'Directory': fd.setFileMode(QtGui.QFileDialog.Directory) elif fdFileMode == 'DirectoryOnly': fd.setFileMode(QtGui.QFileDialog.DirectoryOnly) #--- FileDialog Params ---# if fdRoot is not None: fd.setDirectory(fdRoot) if fdRoots is not None: fd.setSidebarUrls(fdRoots) if fdFilters is not None: fd.setFilters(fdFilters) if fdCmd is not None: # noinspection PyUnresolvedReferences fd.accepted.connect(fdCmd) #--- Result ---# return fd
def __initUI(self): layout = QtGui.QGridLayout() self.scandisplay = scanview.ScanImageDisplay() #img = QtGui.QImage(600,480,QtGui.QImage.Format_RGB32) #img.load("1.png") #self.scandisplay.setImage(img) #createlineimage(img) #self.scandisplay.setLineImage(img) layout.addWidget(self.scandisplay) self.__progressbar = QtGui.QProgressBar() self.__progressbar.setRange(0,self.rotations) layout.addWidget(self.__progressbar) self.setWindowTitle('Splinesweep v1.0 - \"Withnail\"') #Initializing control widget self.controlwidget = QtGui.QWidget() self.controllayout = QtGui.QGridLayout() self.controlwidget.rotation_spinbox = QtGui.QSpinBox() self.controlwidget.rotation_spinbox.setRange(0,10000) self.controlwidget.rotation_spinbox.setValue(300) self.controlwidget.rotation_label = QtGui.QLabel("Number of rotations") self.controlwidget.splinegen_button = QtGui.QPushButton("Generate a spline") self.controlwidget.channel_combobox = QtGui.QComboBox() self.controlwidget.channel_combobox.addItem("Red") self.controlwidget.channel_combobox.addItem("Green") self.controlwidget.channel_combobox.addItem("Blue") self.controlwidget.save_filedialog = QtGui.QFileDialog() self.controlwidget.save_filedialog.setFileMode(QtGui.QFileDialog.AnyFile) self.controlwidget.save_filedialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) self.controlwidget.save_filedialog.setFilter("Wavefront Obj File (*.obj)") self.controlwidget.save_filedialog.setDefaultSuffix("obj") self.controlwidget.save_filedialog.setVisible(False) self.controlwidget.scan_button = QtGui.QPushButton("Start Scan") self.controllayout.addWidget(self.controlwidget.rotation_label,0,0) self.controllayout.addWidget(self.controlwidget.rotation_spinbox,0,1) self.controllayout.addWidget(QtGui.QLabel("Color channel"),1,0) self.controllayout.addWidget(self.controlwidget.channel_combobox,1,1) self.controllayout.addWidget(self.controlwidget.splinegen_button,2,0,1,2) self.controllayout.addWidget(self.controlwidget.scan_button,3,0,1,2) self.controlwidget.setLayout(self.controllayout) layout.addWidget(self.controlwidget,0,1,2,1) self.setLayout(layout) #Connecting signals/slots self.connect(self.controlwidget.rotation_spinbox,QtCore.SIGNAL("valueChanged(int)"),self.setRotations) self.connect(self.controlwidget.splinegen_button,QtCore.SIGNAL("pressed()"),self.updateSplineDisplay) self.connect(self.controlwidget.channel_combobox,QtCore.SIGNAL("activated(QString)"),self.setColorChannel) self.connect(self.controlwidget.scan_button,QtCore.SIGNAL("pressed()"),self.showSaveDialog) self.connect(self.controlwidget.save_filedialog,QtCore.SIGNAL("filesSelected(QStringList)"), self.performScan)
def unzip(self): file_dialog = QtGui.QFileDialog() file_path = file_dialog.getOpenFileNameAndFilter( caption=QString(u"选择zip文件"), filter="*.zip")[0] file_path = unicode(file_path) # .encode("utf-8") print file_path file_path = file_path.encode("gbk") file_dialog = QtGui.QFileDialog() dir_path = file_dialog.getExistingDirectory(caption=QString(u"解压到目录")) dir_path = unicode(dir_path) # .encode("utf-8") print dir_path.replace("\\", "/") dir_path = dir_path.encode("gbk") if file_path and dir_path: args = ("bin/unzip.exe", file_path, "-d", dir_path) self.CMD_DONE = False thread.start_new_thread(self.do_cmd, args) while not self.CMD_DONE: time.sleep(0.5) self.info_box.append(u"解压缩zip完成...")
def testBrowseButtonClicked(self): self.fileDialog = QtGui.QFileDialog() self.detectFilePath = self.getFileName() print self.detectFilePath self.DetectDataFile.setText(self.detectFilePath) # deprecated self.XmlFileName = self.detectFilePath #read CSV files GDF files will be supported later Details = {} TrainingFileClass.getClasses(self.detectFilePath) Details["SubjectName"] = TrainingFileClass.getName(self.detectFilePath) Details["Classes"] = TrainingFileClass.getClasses(self.detectFilePath) self.testDataSubjectName.setText( Details["SubjectName"]) #subject name label
def on_browse_button(self, butt): ki = str(butt.property("ki").toString()) #print "on_dir_select", ki fileDialog = QtGui.QFileDialog(self) fileDialog.setFileMode(QtGui.QFileDialog.DirectoryOnly) fileDialog.setMinimumWidth(700) fileDialog.setMinimumHeight(700) if fileDialog.exec_(): #print fileDialog.selectedFiles()[0] path = fileDialog.selectedFiles()[0] #self.settings.setValue("paths\%s" % ki, QtCore.QVariant( path ) ) #self.txt[ki].setText( path ) self.set_path_from_raw(ki, path)
def guardarArchivoPython(self): u""" Muestra un cuadro de dialogo desde donde seleccionar un archivo. """ nombre_archivo = unicode(self.leNombreClase.text().toUtf8(), 'utf-8') dialog = QtGui.QFileDialog() dialog.setFileMode(QtGui.QFileDialog.Directory) filename = dialog.getSaveFileName(self, 'Abrir archivo Python', filter='*.py') if filename != '': filename = unicode(filename, 'utf-8') + '.py' return filename else: return ''
def exPort(self): "exports character order" fd = QtGui.QFileDialog() fd.setWindowIcon(self.windowIcon()) title = 'Export character order...' savePath = fd.getSaveFileName(self, title, self.eximportDir, '.txt') if not savePath: return self.eximportDir = os.path.dirname(_str(savePath)) with open(_str(savePath), 'wb') as dst: dst.write(_str('').join(self.getOrder()).encode('utf-8')) line = "Exported digit order to '{}'" self.infoLabel.setText(line.format(os.path.basename(_str(savePath))))
def new_file_dialog(self, filename=None): dialog = qg.QFileDialog() dialog.setWindowTitle('Choose binary') dialog.setFileMode(qg.QFileDialog.AnyFile) if filename is None: if dialog.exec_(): filename = str(dialog.selectedFiles()[0]) else: raise Exception('Failed to open dialog') arch = self.open_arch_dialog() print(repr(filename), arch) return filename, arch
def open_file(self): helper.reset_values() file = open("../../output/output.txt", "w").close() self.out_text.clear() name = QtGui.QFileDialog.getOpenFileName(QtGui.QFileDialog(), "Open File") self.make_ui() if name: file = open(name, 'r') helper.read_file(name) with file: text = file.read() self.code_text.setText(text) else: print("invalid file")
def outFile(self): # by Carson Farmer 2008 # display file dialog for output shapefile self.outShp.clear() fileDialog = QtGui.QFileDialog() fileDialog.setConfirmOverwrite(False) outName = fileDialog.getSaveFileName(self, "Output Shapefile", ".", "Shapefiles (*.shp)") outPath = QtCore.QFileInfo(outName).absoluteFilePath() if not outPath.upper().endswith(".SHP"): outPath = outPath + ".shp" if outName: self.outShp.clear() self.outShp.insert(outPath)
def exportGraph(self): dlg = QtGui.QFileDialog() dlg.setFileMode(QtGui.QFileDialog.DirectoryOnly) dlg.exec_() folderName = dlg.selectedFiles() if isEmpty(self.graph): print("The Graph is Empty.") else: epsilon = float(self.eValueHolder.text()) anonimizeDegreeSequence = anonimizer(self.graph, epsilon) drawHistogram(anonimizeDegreeSequence, "modifiedHistogram", folderName[0] + "/") self.modifiedHistogramHolder.setPixmap( QtGui.QPixmap('images/modifiedHistogram.png'))
def _browse_clicked(self): """ Descript. : """ get_dir = QtGui.QFileDialog(self) given_dir = self._base_image_dir d = str( get_dir.getExistingDirectory(self, given_dir, "Select a directory", QtGui.QFileDialog.ShowDirsOnly)) d = os.path.dirname(d) if d is not None and len(d) > 0: self.set_directory(d)
def file_import(self): fd = QtGui.QFileDialog(self) fname = fd.getOpenFileName( parent=self, caption=self.tr("请选择要导入的文本文件"), filter=QString("Text File(*.txt);;Any File(*.*)")) fname = unicode(fname) if os.path.isfile(fname): fp = codecs.open(fname, 'r') content = fp.read() encoding_det = chardet.detect(content).get('encoding') content = content.decode(encoding_det) self.ui.textEdit.setPlainText(content)
def OnSelectPath(self): """ Select the data directory. Once a folder is selected, call additional functions to read in settings if they exist. """ fd = QtGui.QFileDialog() if self.datPathLineEdit.text() != "": fd.setDirectory(self.datPathLineEdit.text()) path = fd.getExistingDirectory() if path: self.datPathLineEdit.setText(path) self.OnDataPathChange()
def uploadEvent(self): """ 上传按钮点击后的触发事件,弹出上传界面窗口 如果时上传文件到组中时,需要制定访问策略 """ #print 'The current index is : ' , self.ui.tabWidget.currentIndex() # 产看当前页面是在个人空间页面还是组空间页面 fd = QtGui.QFileDialog(self) fd.setDirectory(QtCore.QString("./datamodel/upload/")) if fd.exec_() == QtGui.QDialog.Accepted: result = QtCore.QStringList(fd.selectedFiles()) ans = [] for i in range(result.count()): temp = repr(result[i]) ans.append(temp) del fd del result self.uploadFile['filename'] = repr(ans) if self.ui.tabWidget.currentIndex() == 0: # 表示上传到个人空间 #self.showUI.setFilenames(ans, self.containerName) self.uploadFile['username'] = self.userInfo['username'] self.uploadFile['groupname'] = self.userInfo['username'] self.uploadFile['container'] = self.containerName self.uploadFile['Auth Token'] = self.userInfo['Auth Token'] self.uploadFile['StorageURL'] = self.userInfo['StorageURL'] self.showUI.setUploader(self.uploadFile) self.uploadFile = {} self.showUI.ui.tabWidget.setCurrentWidget(self.showUI.ui.tab) self.showInfoWindow() # show上传下载界面 else: # 表示上传到组空间 if self.currentGroupContainer == None or self.currentGroup == None: QtGui.QMessageBox.about(self, 'Attention', 'Please select the group you want to upload!') return if 'GroupAttr' not in self.groupInfo[self.currentGroup]: res = util.groupInfo(self.currentGroup, self.userInfo['username']) ml = [] for user in res['users']: ml.append(user['name']) if self.currentGroup not in self.groupInfo: self.groupInfo[self.currentGroup] = {'GroupAttr':res['account_attr'], 'MemberList' : ','.join(ml), 'GroupInfo': res['account_inst']} else: self.groupInfo[self.currentGroup]['GroupAttr'] = res['account_attr'] self.groupInfo[self.currentGroup]['GroupInfo'] = res['account_inst'] self.groupInfo[self.currentGroup]['MemberLlist'] = ml self.policyDialog.initAttributeList(self.groupInfo[self.currentGroup]['GroupAttr'].split(',')) self.policyDialog.show() else: print 'wrong'
def save_character(self): widget = QtGui.QFileDialog() filename = widget.getSaveFileName(None, "Zapisz postac Vorago", "", "Vorago Character (*.vch)") if filename == "": ui.Status.setText("Blad: Postac nie zapisana.") return self.update_character() # Set race, name etc. f = open(filename, "w") pickle.dump(ch, f) f.close() ui.Status.setText("OK: Postac zapisana.")
def loadConfig(self): """Loads config from file and rebuilds whole tree""" l_fileName = QtGui.QFileDialog().getOpenFileName(self, self.tr(u"Otwórz"), QtCore.QString(settings.module_abs_path()), "Pliki UGMa (*.ugm)") if l_fileName == "": return self.fileName = unicode(l_fileName) l_shortFileName = os.path.split(unicode(l_fileName))[1] self.setWindowTitle(QtGui.QApplication.translate("UGMMainWidget", "UGM Configuration - %s" % (l_shortFileName), None, QtGui.QApplication.UnicodeUTF8)) self.configManager.update_from_file(self.fileName) l_attributesConfig = self.configManager.get_attributes_config() self._initModel(UGMPropertiesModel(l_attributesConfig['attributes_def'], l_attributesConfig['attributes_for_elem'], self.configManager.get_ugm_fields()))
def browseClicked(): # browseClicked in chessboard cameraCalib.plainTextEdit.setPlainText("") dialog = QtGui.QFileDialog(None, "Select Image Directory") dialog.setFileMode(QtGui.QFileDialog.Directory) dialog.setDirectory(wrk_drr) dialog.setOption(QtGui.QFileDialog.ShowDirsOnly) dialog.exec_() global path_calib try: path_calib = dialog.selectedFiles()[0] cameraCalib.plainTextEdit_3.setPlainText(path_calib) except: print "no image directory choosen" return False
def on_export(self): # #QProgressDialog !!! vCurrent = self.tabWidget.currentWidget() # Current tab. f = QtGui.QFileDialog() input = f.getExistingDirectory(vCurrent, 'Select a folder to export into :', os.getcwd()) if input: input = str(input.toUtf8()) vRet = vCurrent.b.ExportAll(input) QtGui.QMessageBox.information(vCurrent, 'Export', 'Export finished !')
def on_actionLoad_triggered(self, checked=None): if checked is None: return dialog = QtGui.QFileDialog(self) dialog.setFileMode(QtGui.QFileDialog.AnyFile) dialog.setAcceptMode(QtGui.QFileDialog.AcceptOpen) if not dialog.exec_(): return filename = dialog.selectedFiles()[0] self.initial_path = pickle.load(open(filename)) self.nebrunner.run(self.coords1, self.coords2, run=False, path=self.initial_path)
def openfeff(self): dlg = QtGui.QFileDialog() dlg.setFileMode(QtGui.QFileDialog.ExistingFiles) dlg.setAcceptMode(0) # open dialog dlg.setNameFilters(["All files (*.*)"]) # dlg.setDirectory(os.getcwd()) if dlg.exec(): self.fnfeff = dlg.selectedFiles() else: return self.fnfeff.sort() #Extract amplitude and phase from feff files and save to disk for i in range(len(self.fnfeff)): state = 0 data = [] f = open(self.fnfeff[i]) for line in f: cols = line.split() if cols[0] == '-----------------------------------------------------------------------': state = 1 continue if cols[0] == 'k': state = 2 continue if state == 1: r = float(cols[2]) state = 0 continue if state == 2: data.append(cols) new_data_amp = [] new_data_pha = [] for j in range(len(data)): k = float(data[j][0]) pha = float(data[j][1]) + float(data[j][3]) amp = float(data[j][2]) * np.exp( -2 * r / float(data[j][5])) * float(data[j][4]) new_data_amp.append([k, amp]) new_data_pha.append([k, pha]) np.savetxt(self.fnfeff[i] + '.amp', new_data_amp) np.savetxt(self.fnfeff[i] + '.pha', new_data_pha) for j in range(len(self.shellPha)): self.shellAmp[j].addItem(self.fnfeff[i] + '.amp') for j in range(len(self.shellPha)): self.shellPha[j].addItem(self.fnfeff[i] + '.pha')