Example #1
27
def getOpenFileNamesAndFilter(parent=None, caption="", directory="",
                              filter="", initialFilter="",
                              options=QFileDialog.Options()):
    """
    Module function to get a list of names of files for opening and the
    selected file name filter.
    
    @param parent parent widget of the dialog (QWidget)
    @param caption window title of the dialog (string)
    @param directory working directory of the dialog (string)
    @param filter filter string for the dialog (string)
    @param initialFilter initial filter for the dialog (string)
    @param options various options for the dialog (QFileDialog.Options)
    @return list of file names to be opened and selected filter
        (list of string, string)
    """
    if Globals.isLinuxPlatform():
        options |= QFileDialog.DontUseNativeDialog
    newfilter = __reorderFilter(filter, initialFilter)
    if PYQT_VERSION_STR >= "5.0.0":
        return QFileDialog.getOpenFileNames(
            parent, caption, directory, newfilter, initialFilter, options)
    else:
        return QFileDialog.getOpenFileNamesAndFilter(
            parent, caption, directory, newfilter, initialFilter, options)
Example #2
17
    def choose_dir(self, mode):
        """
		Pass which mode to open the folder explorer in:
		'f': directory
		'a': files
		Or pass a predefined path
		"""
        if mode == "a":
            name = QFileDialog.getOpenFileName(self, "Choose archive", filter=utils.FILE_FILTER)
            name = name[0]
        elif mode == "f":
            name = QFileDialog.getExistingDirectory(self, "Choose folder")
        elif mode:
            if os.path.exists(mode):
                name = mode
            else:
                return None
        head, tail = os.path.split(name)
        name = os.path.join(head, tail)
        parsed = utils.title_parser(tail)
        self.title_edit.setText(parsed["title"])
        self.author_edit.setText(parsed["artist"])
        self.path_lbl.setText(name)
        l_i = self.lang_box.findText(parsed["language"])
        if l_i != -1:
            self.lang_box.setCurrentIndex(l_i)

        if gallerydb.GalleryDB.check_exists(tail):
            self.file_exists_lbl.setText('<font color="red">Gallery already exists</font>')
            self.file_exists_lbl.show()
        else:
            self.file_exists_lbl.hide()
Example #3
0
def make_file_dialog(name_filters, file_mode, directory, parent, native):
    dialog = QFileDialog(parent)
    dialog.setOption(QFileDialog.DontUseNativeDialog, not native)
    dialog.setDirectory(directory)
    dialog.setFileMode(file_mode)
    dialog.setNameFilter(dialog.tr(name_filters))
    return dialog
Example #4
0
    def exportSinglePost(self, post):
        # Here I need to get the post, convert it to dict, and put it into a text file.
        postAsDict = ujson.loads(post)
        if len(postAsDict["Body"]) < 25:
            fileName = postAsDict["Body"]
        else:
            fileName = postAsDict["Body"][0:25] + ".."
        from PyQt5.QtWidgets import QFileDialog

        dialog = QFileDialog()
        filePath = dialog.getSaveFileName(None, "Please select a location to save a post.", fileName + ".txt")
        filePath = filePath[0]
        postText = u"""%s\n
by %s, at %s\n
Gathered from Aether network. Aether is a distributed network of anonymous forums. Join us at www.getaether.net.
This post is licensed under CC-BY-SA.""" % (
            postAsDict["Body"],
            postAsDict["OwnerUsername"],
            str(datetime.utcfromtimestamp(float(postAsDict["CreationDate"]))),
        )
        postText = postText.encode("utf8")
        f = open(filePath, "wb")
        f.write(postText)
        f.close()
        return True
Example #5
0
 def openAfterMaybeSave(self):
     """
     This is the method that initiates file opening. It is called by
     actionOpenSlot to spawn a QFileDialog and connect it to a callback
     method.
     """
     path = self._file_open_path
     if util.isWindows():  # required for native looking file window#"/",
         fname = QFileDialog.getOpenFileName(
                     None,
                     "Open Document", path,
                     "cadnano1 / cadnano2 Files (*.nno *.json *.cadnano)")
         self.filesavedialog = None
         self.openAfterMaybeSaveCallback(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
                     self.win,
                     "Open Document",
                     path,
                     "cadnano1 / cadnano2 Files (*.nno *.json *.cadnano)")
         fdialog.setAcceptMode(QFileDialog.AcceptOpen)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.fileopendialog = fdialog
         self.fileopendialog.filesSelected.connect(self.openAfterMaybeSaveCallback)
         fdialog.open()
Example #6
0
 def openBuildPathFileDialog(self):
     brows = QFileDialog()
     self.getPath = brows.getExistingDirectory(self,
                                               "Select Directory",
                                               expanduser("~"),
                                               QFileDialog.ShowDirsOnly)
     self.buildLocationEdit.setText(self.getPath)
Example #7
0
 def saveFileDialog(self):
     fname = self.filename()
     if fname == None:
         directory = "."
     else:
         directory = QFileInfo(fname).path()
     if util.isWindows():  # required for native looking file window
         fname = QFileDialog.getSaveFileName(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         self.writeDocumentToFile(fname)
     else:  # access through non-blocking callback
         fdialog = QFileDialog(
                         self.win,
                         "%s - Save As" % QApplication.applicationName(),
                         directory,
                         "%s (*.json)" % QApplication.applicationName())
         fdialog.setAcceptMode(QFileDialog.AcceptSave)
         fdialog.setWindowFlags(Qt.Sheet)
         fdialog.setWindowModality(Qt.WindowModal)
         self.filesavedialog = fdialog
         self.filesavedialog.filesSelected.connect(
                                             self.saveFileDialogCallback)
         fdialog.open()
    def saveFile(self):
        e = TExtension()
        e.name = self.nameEdit.text() or None
        e.version = self.versionEdit.text() or None
        e.developer = self.developerEdit.text() or None
        e.developerURL = self.developerURLEdit.text() or None

        e.resourcesPath = self.resourcesRootBox.currentFolder()
        e.libPath = self.scriptRootBox.currentFolder()

        e.launchAtStartup = self.launchAtStartupBox.isChecked()
        e.mainScript = self.mainScriptDrop.currentText()
        # Note. for now we always do a list.
        addToMenu = []
        for ok, path, name, shortcut in self.addScriptsView.list():
            if not ok:
                continue
            data = dict(path=path, name=name, shortcut=shortcut)
            for k, v in data.items():
                if v is None:
                    del data[k]
            addToMenu.append(data)
        if addToMenu:
            e.addToMenu = addToMenu
        e.tfVersion = self.tfVersionEdit.text() or None

        # TODO: switch to directory on platforms that need it
        dialog = QFileDialog(self, self.tr("Save File"), None, "TruFont Extension (*.tfExt)")
        dialog.setAcceptMode(QFileDialog.AcceptSave)
        ok = dialog.exec_()
        if ok:
            path = dialog.selectedFiles()[0]
            e.save(path)
Example #9
0
    def _connect(self, src):
        try:
            self.cnxn = pyodbc.connect(driver='{Microsoft Access Driver (*.mdb)}', DBQ=src)
        except pyodbc.Error as error:
            raise _DatabaseServerError(error.__str__())

        # Check images folder
        self.imgDir = QtCore.QDir(src)
        if not self.imgDir.cd('../../CoinImages'):
            directory = QFileDialog.getExistingDirectory(self.parent(),
                            self.tr("Select directory with images"),
                            OpenNumismat.HOME_PATH)
            if directory:
                self.imgDir = QtCore.QDir(directory)
            else:
                return False

        # Check predefined images folder
        self.defImgDir = QtCore.QDir(src)
        if not self.defImgDir.cd('../../Images'):
            directory = QFileDialog.getExistingDirectory(self.parent(),
                            self.tr("Select directory with pre-defined images"),
                            OpenNumismat.HOME_PATH)
            if directory:
                self.defImgDir = QtCore.QDir(directory)
            else:
                return False

        return self.cnxn.cursor()
    def saveDataFiles(self, activated=False, filePath = None):
        if len(self.df.keys())!=0:
            for k, v in self.df.items():
                f_name, f_ext = os.path.splitext(self.file_name_dict[k])
                candidate_file_path = '{0}-fixed{1}'.format(f_name, f_ext)
                filePath, _ = QFileDialog.getSaveFileName(None, 'Save CSV File', candidate_file_path, "CSV files (*.csv)")

                if len(filePath) is not 0:
                    logger.debug("Saving CSV file: {0}".format(filePath))
                    df = v.copy()
                    col_n = df.as_matrix().shape[1]/2

                    col_names = np.array([('x{0}'.format(i), 'y{0}'.format(i)) for i in range(int(round(col_n)))]).flatten()
                    df.columns = pd.Index(col_names)
                    df.to_csv(filePath)

        for k, v in self.line_data_dict.items():
            f_name, f_ext = os.path.splitext(self.file_name_dict[k])
            candidate_file_path = '{0}-fixed{1}'.format(f_name, f_ext)
            filePath, _ = QFileDialog.getSaveFileName(None, 'Save JSON File', candidate_file_path, "JSON files (*.json)")

            if len(filePath) is not 0:
                logger.debug("Saving JSON file: {0}".format(filePath))
                with open(filePath, 'w') as f_p:
                    json.dump(v, f_p)
Example #11
0
 def on_save(self):
     d = QFileDialog()
     save_dir = d.getExistingDirectory()
     pl_file = open(path.join(save_dir, self.edToolName.text() + '.xml'), 'w')
     pl_file.write(self.create_pipeline())
     pl_file.close()
     self._parent.close()
Example #12
0
 def SelectVideoGPX(self):
     if os.name == 'nt':
         ffmpeg = os.path.dirname(__file__)+'/FFMPEG/ffmpeg.exe'
         versione = 'ffmpeg.exe'
     else:
         ffmpeg = os.path.dirname(__file__)+'/FFMPEG/./ffmpeg'
         versione = 'ffmpeg'
     if os.path.exists(ffmpeg) == True:
         self.comboBox.clear()
         if self.player.state() == QMediaPlayer.PlayingState:
             self.player.pause()    
         self.videofile = None
         self.GPXfile = None
         options = QFileDialog.Options()
         options |= QFileDialog.DontUseNativeDialog
         self.videofile, _ = QFileDialog.getOpenFileName(self,"Select Video File", "","All Files (*);;Video File (*.mp4 *.avi *.ogv)", options=options)
         if self.videofile:        
             self.GPXfile, _ = QFileDialog.getOpenFileName(self,"Select GPX file", "","All Files (*);;Video File (*.gpx)", options=options)
             if self.GPXfile:
                 self.ParseGpx(self.GPXfile)
                 self.LoadVideo(self.videofile)
                 self.replayPosition_label.setText( "-:- / -:-")
     else:
         ret = QMessageBox.warning(self, "Warning", 'missing ffmpeg binaries, please download it from https://github.com/sagost/VideoUavTracker/blob/master/FFMPEG/'+versione+' and paste it in /.qgis3/python/plugins/Video_UAV_Tracker/FFMPEG/ ', QMessageBox.Ok)
         self.close()
    def pullDataNREL (self):
        missingD = self.checkForMissingInfo()

        print (self.textboxName.text())
        print (self.textboxEmail.text())
        print (self.textboxReason.text())
        print (self.textboxInterval.text())
        print (self.textboxAffiliation.text())
        print (self.textboxAPI.text())
        print (self.textboxYear.text())
        
        # Check for missing info.
        if len(missingD) != 0:
            QMessageBox.critical(self, "Missing information", "The following info. is missing: " + missingD, QMessageBox.Ok, QMessageBox.Ok)
            return

        self.meshFile = QFileDialog.getOpenFileName(self, 'Select Mesh File (.csv)', '/home')
        self.savingDirectory = QFileDialog.getExistingDirectory(self, 'Select Saving Directory', '/home')

        # Check that mesh file path isn't empty.
        if len(self.meshFile) == 0:
            QMessageBox.critical(self, "Missing Mesh File", "Please select a mesh file.", QMessageBox.Ok, QMessageBox.Ok)
            return

        # Check that the folder path isn't empty.
        if len(self.savingDirectory) == 0:
            QMessageBox.critical(self, "Missing Mesh File", "Please select a folder to save.", QMessageBox.Ok, QMessageBox.Ok)
            return

        print (self.meshFile[0])
        print (self.savingDirectory)
        
        NRELData.create_folders (self.savingDirectory, self.textboxYear.text())
        NRELData.get_data (self.meshFile[0], self.savingDirectory, self.textboxYear.text(), self.textboxInterval.text(), self.textboxName.text(), self.textboxEmail.text(), self.textboxReason.text(), self.textboxAffiliation.text(), self.textboxAPI.text(), 'false')
Example #14
0
        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)
Example #15
0
 def Convert():
     func = Functions()
     InFile = getattr(self, convertID+'InEdit').text()
     if InFile:
         dialog = QFileDialog()
         dialog.raise_()
         fileName, _ = dialog.getSaveFileName(self, "Save As...", InFile, "All Files (*.*)", options=QFileDialog.Options())
         if fileName:
             convertBtn = getattr(self, convertID+'ConvertBtn')
             old_text = convertBtn.text()
             convertBtn.setText('proc...')
             self.setEnabled(False)
             QApplication.processEvents()
             if fileName != InFile:
                 print("Saving file as "+ fileName)
                 if convertID == "At3":
                     if self.At3EditorEdit.text() and self.FFEditorEdit.text():
                         func.At3Convert(InFile, fileName)
                     else:
                         self.make_ErrorMessage("FFMpeg or the At3Tool has not been configured in the settings.")
                 elif convertID == "Vid":
                     if self.FFEditorEdit.text():
                         func.VidConvert(InFile, fileName)
                     else:
                         self.make_ErrorMessage("FFMpeg has not been configured in the settings.")
                 elif convertID == "Pmf":
                     func.PmfConvert(InFile, fileName)
                 convertBtn.setText(old_text)
             else:
                 self.make_ErrorMessage("You can't save over the file you are converting!")
             self.setEnabled(True)
     else:
         self.make_ErrorMessage('You are missing an input file.')
Example #16
0
    def saveCSVFile(self, activated=False, filePath = None):
        if self.df is None or self.df_dist is None or self.df_region is None or self.relation_matrix is None:
            return

        dirctory = os.path.dirname(self.filePath)
        base_name = os.path.splitext(os.path.basename(self.filePath))[0]

        path = os.path.join(dirctory, '{0}-info.txt'.format(base_name))
        filePath, _ = QFileDialog.getSaveFileName(None, 'Save TXT File', path, "TXT files (*.txt)")
        names = list(map(lambda x: x.data(Qt.UserRole), self.getCol(0)))
        items = [self.graphics_items[name] for name in names]
        point_list = list(filter(lambda x:type(x[1]) is FigureType.Point.value, zip(names, items)))
        if len(filePath) is not 0 and len(point_list) is not 0:
            logger.debug("Saving CSV file: {0}".format(filePath))
            with open(filePath, "w") as fp:
                for name, item in point_list:
                    fp.write('{0} : {1}'.format(name, item.getPoints()))

        for attr in ['distance', 'region']:
            path = os.path.join(dirctory, '{0}-{1}.csv'.format(base_name, attr))
            filePath, _ = QFileDialog.getSaveFileName(None, 'Save CSV File', path, "CSV files (*.csv)")

            if len(filePath) is not 0:
                logger.debug("Saving CSV file: {0}".format(filePath))
                if attr=='distance':
                    self.df_dist.to_csv(filePath)
                elif attr=='region':
                    self.df_region.to_csv(filePath)

        path = os.path.join(dirctory, '{0}-relation.csv'.format(base_name))
        filePath, _ = QFileDialog.getSaveFileName(None, 'Save CSV File', path, "CSV files (*.csv)")
        if len(filePath) is not 0:
            pd.DataFrame(self.relation_matrix).to_csv(filePath)

        self.savedFlag = True
    def sortVideo(self):

        dialog = QFileDialog()
        folder = dialog.getExistingDirectory(self, 'Select output directory for thumbnail images')
        if folder:
            if self.filename:
                self.getThread = VideoSort(self.filename, folder, 'frame')
                #self.results.setIconSize(QtCore.QSize(self.getThread.thumbInfo['resolution'][0], self.getThread.thumbInfo['resolution'][1]))
                #slot
                self.getThread.resultsSignal.connect(self.setFeatures)
                self.getThread.start()
                self.player.setMedia(QMediaContent(QtCore.QUrl.fromLocalFile(self.filename)))
                self.currentMedia = self.filename

            if self.directory:
                formatList = ['.mp4', '.mov', '.mkv', '.avi']
                for dirname, dirnames, filenames in os.walk(self.directory):
                    supportedFiles = [os.path.abspath(os.path.join(dirname, path)) for path in filenames if os.path.splitext(path)[1] in formatList]

                for filename in supportedFiles:
                    self.getThread = VideoSort(filename, folder, os.path.splitext(filename.split('/')[-1])[0])
                    self.getThread.resultsSignal.connect(self.setFeatures)
                    self.getThread.start()
                    self.player.setMedia(QMediaContent(QtCore.QUrl.fromLocalFile(filename)))
                #Just set the last file as the current file
                self.player.setMedia(QMediaContent(QtCore.QUrl.fromLocalFile(filename)))
                self.currentMedia = filename
Example #18
0
 def add_file(self):
     """Add files or directories to the list of files/directories"""
     file_dialog = QFileDialog(self)
     if file_dialog.exec_():
         filenames = file_dialog.selectedFiles()
         self.ui.listWidget.addItems(filenames)
         self.ui.encryptButton.setEnabled(True)
Example #19
0
 async def get_save_filename(parent, title, url, filtr):
     dialog = QFileDialog(parent, title, url, filtr)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     result = await dialog_async_exec(dialog)
     if result == QFileDialog.AcceptSave:
         return dialog.selectedFiles()
     else:
         return []
Example #20
0
File: SafeB.py Project: lebik/SafeB
 def showDialog(self):
     if self.radio1.isChecked():
         path = QFileDialog.getOpenFileName()
     else:
         path = QFileDialog.getExistingDirectory()
     if ''.join(path) != '':
         config.path = ''.join(path)
         self.line_edit.setText(config.path)
Example #21
0
 def __open_dialog__(title, file_types, dir, setup_dialog, parent=None):
     dialog = QFileDialog(parent)
     if file_types: dialog.setNameFilter(file_types)
     dialog.setDirectory(dir)
     dialog.setWindowTitle(title)
     setup_dialog(dialog)
     dialog.finished.connect(lambda: dialog.deleteLater())
     dialog.show()
 def _browse_files(self):
     '''
     Pops file dialog window up.
     :returns: path to selected file
     '''
     file_dialog = QFileDialog()
     file_dialog.setFileMode(QFileDialog.ExistingFile)
     return file_dialog.getOpenFileName()[0]
Example #23
0
File: wizard.py Project: khuno/rpg
 def openPatchesPageFileDialog(self):
     brows = QFileDialog()
     self.getPath = brows.getOpenFileName(self,
                                          "Choose patches",
                                          "/home",
                                          "All files (*)")
     self.newPath = self.getPath[0]
     self.listPatches.addItem(self.newPath)
 def upload_python_clicked(self):
     file_dialog = QFileDialog()
     file_dialog.setFileMode(QFileDialog.AnyFile)
     file = file_dialog.getOpenFileName(self, 'Open Python File', '', "Python Files (*.py)") 
     for line in re.split("/",str(file[0])):
         if ".py" in line:
             global pyfile
             pyfile = line
Example #25
0
 def actionExport(self):
     if using_qt5:
         export_as = QFileDialog.getSaveFileName(self, "Export as...")[0]
     else:
         export_as = QFileDialog.getSaveFileName(self, "Export as...")
     create_code = codegen.codegen(self, "mynode", self.blocks, self.resolution)
     if export_as != "":
         create_code.writeToFile(export_as)
Example #26
0
 def browseButton_clicked(self):
     if self.operation == IMPORT_CSV:
         path = QFileDialog.getOpenFileName(self, 'Import spreadsheet', '', '*.csv')[0]
     elif self.operation == EXPORT_CSV:
         path = QFileDialog.getSaveFileName(self, 'Export spreadsheet', '', '*.csv')[0]
     else:
         path = QFileDialog.getExistingDirectory(self, 'Export spreadsheets')
     if path:
         self.pathLabel.setText(path)
 def getFolderPath(self):
     """
     Get the path to the folder where the images with the pattern are stored
     """
     diag = QFileDialog()
     srcFolder = diag.getExistingDirectory(parent=diag, caption="Chose directory",
                                         directory=os.getenv('HOME'))
     self.srcFolder = srcFolder
     return srcFolder
Example #28
0
 def __init__(self):
     QFileDialog.__init__(self)
     self.setOption(self.DontUseNativeDialog, True)
     self.setFileMode(self.ExistingFiles)
     butns = self.findChildren(QPushButton)
     self.butn = [x for x in butns if 'open' in str(x.text()).lower()][0]
     self.butn.clicked.disconnect()
     self.butn.clicked.connect(self.clicked)
     self.tree = self.findChild(QTreeView)
Example #29
0
 def open_files(self, mode):
     a = QFileDialog()
     if mode == 1:
         v = a.getOpenFileNames(caption="Импорт файлов rpm...", filter="RPM Files (*.rpm);;Any files (*.*)")[0]
         return json.dumps(v)
     elif mode == 2:
         directory = a.getExistingDirectory(options=QFileDialog.ShowDirsOnly)[0]
         return json.dumps(directory)
     elif mode == 3:
         return json.dumps(a.getOpenFileName()[0])
Example #30
0
	def openExplorer(self):
		if self.folder:
			path = QFileDialog.getExistingDirectory(self,
										   'Choose folder')
		else:
			path = QFileDialog.getOpenFileName(self,
									  'Choose file')
			path = path[0]
		if len(path) != 0:
			self.setText(path)
Example #31
0
 def btnSaveChart_CLick(self):
     p = self.frameChart.grab()
     filename, _ = QFileDialog.getSaveFileName(
         None, "Save series chart as a image", "", "Image Files (*.png)")
     p.save(filename, "PNG")
     print("Chart series image saved to: ", filename)
Example #32
0
 def on_browseBackupFolder_clicked(self, widget):
     fname = QFileDialog.getExistingDirectory(self.window(), 'Open file', '/home/{}'.format(getpass.getuser()))
     self.pathToBackupFolder.setText(fname)
 def on_actionOuvrir_triggered(self):
     (nomfichier, filtre) = QFileDialog.getOpenFileName(
         self, 'Ouvrir fichier', filter="Bibliothèque (*.deb);; Tout (*.*)")
     if nomfichier:
         QMessageBox.information(self, 'Trace',
                                 'Nom du fichier {}'.format(nomfichier))
Example #34
0
 def open(self):
     fileName = ""
     dialog = QFileDialog()
     dialog.setFileMode(QFileDialog.AnyFile)
     dialog.setNameFilter("EbookCreator (book.qml);;All (*)")
     dialog.setWindowTitle("Load Ebook")
     dialog.setOption(QFileDialog.DontUseNativeDialog, True)
     dialog.setAcceptMode(QFileDialog.AcceptOpen)
     dialog.setDirectory(os.path.join(self.install_directory, "sources"))
     if dialog.exec_():
         fileName = dialog.selectedFiles()[0]
     del dialog
     if not fileName:
         return
     self.loadBook(fileName)
Example #35
0
def getfile():
    dlg = QFileDialog()
    dlg.setFileMode(QFileDialog.AnyFile)
    if dlg.exec_():
        filenames = dlg.selectedFiles()
        return filenames[0]
Example #36
0
 def database_load_mapping(self):
     filename, _ = QFileDialog.getOpenFileName(self, "Open mapping", "",
                                               "Json files (*.json)")
     load_mapping(self.model, filename)
Example #37
0
 def OpenDialog(self):
     options = QFileDialog.Options()
     options = QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks
     self.curPath = QFileDialog.getExistingDirectory(
         self, 'Open Folder', self.curPath, options)
     self.pathChanged.emit(self.curPath)
Example #38
0
	def openFile(self):
		filename = QFileDialog.getOpenFileName(self, 'Open File', os.getenv('HOME')) 
		f = open(filename, 'r') 
		filedata = f.read() 
		self.text.setText(filedata) 
		f.close()
Example #39
0
 def _save(self):
     filePath, _ = QFileDialog.getSaveFileName(
         self, "保存图像", "",
         "PNG(*.png);;JPEG(*.jpg *.jpeg);;All Files(*.*) ")
     if filePath == "": return
     self.img.save(filePath)
Example #40
0
 def _openImg(self):
     fileName, fileType = QFileDialog.getOpenFileName(
         self, "选取文件", "All Files (*)")
     self.img = QImage(fileName)
     self.oriImg = self.img.copy()
     self._refreshBoard()
Example #41
0
 def openMsg(self):
     file, ok = QFileDialog.getOpenFileName(
         self, "C:/", "All Files (*);;Text Files (*.txt)")
     self.ui.statusBar.showMessage(file)
Example #42
0
    def on_browseFolders_clicked(self, widget):
        index = self.usbDevicesChooser.currentIndex()
        file_dialog = QFileDialog()
        file_dialog.setFileMode(QFileDialog.DirectoryOnly)
        file_dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        file_view = file_dialog.findChild(QListView, 'listView')

        if file_view:
            file_view.setSelectionMode(QAbstractItemView.MultiSelection)

        ftree_view = file_dialog.findChild(QTreeView)

        if ftree_view:
            ftree_view.setSelectionMode(QAbstractItemView.MultiSelection)

        file_dialog.setDirectory(self.usbDevices[index].getPath())

        if file_dialog.exec():
            paths = file_dialog.selectedFiles()

        self.pathToFolders.setText(";".join(paths))
Example #43
0
if __name__ == '__main__':
    QF = QFileDialog.getOpenFileNames
    fns, filetype = QF(
        None,
        "Select a File",
        '//192.168.1.20/jhglb/JHGLB_PUBLIC',  # 起始路径
        "Files (*.jpg *.PNG)")
    im_list = []
    if fns:
        im1 = Image.open(fns[0])
        for i in range(1, len(fns)):
            img = Image.open(i)
            if img.mode == "RGBA":
                img = img.convert('RGB')
                im_list.append(img)
            else:
                im_list.append(img)
    pdf_name = QFileDialog.getSaveFileName(None)
    im1.save(pdf_name,
             "PDF",
             resolution=100.0,
             save_all=True,
             append_images=im_list)

    pdf_name = '3D2.pdf'
    if ".pdf" in pdf_name:
        rea(path='', pdf_name=pdf_name)
    else:
        rea(path='', pdf_name="{}.pdf".format(pdf_name))
Example #44
0
 def btnSaveWorld_Click(self):
     filename, _ = QFileDialog.getSaveFileName(None,
                                               "Save world as a image", "",
                                               "Image Files (*.png)")
     self.frameWorld.img.save(filename, "PNG")
     print("World image saved to: ", filename)
Example #45
0
class MainWindow(QMainWindow):
    def __init__(self):
        super(MainWindow, self).__init__()
        loadUi(abspath(r'src\Qt\GPM_AI_training.ui'), self)
        self.file_path = QFileDialog()

        self.training_data_path = None
        self.testing_data_path = None
        self.training_image_list = None
        self.testing_image_list = None
        self.all_image_list = None

        self.display_type_list = ['Training', 'Testing', 'All']
        self.display_type = 'Training'
        self.sort_type_list = ['Image Type', 'Alphabetical', 'Time']
        self.sort_type = 'Image Type'
        self.label_type_list = ['Without Mark', 'Mark']
        self.label_type = 'Without Mark'

        self.listWidget_ImageName.itemDoubleClicked.connect(self.on_listWidget_ImageName_itemDoubleClicked)

        self.image = QImage()
        self.pix = None
        self.pix_item = None
        self.scene = QGraphicsScene()
        self.image_width = self.graphicsView.width() - 10
        self.image_height = self.graphicsView.height() - 10

    @pyqtSlot()
    def on_pushButton_AIModelPath_3_clicked(self):
        self.training_data_path = self.file_path.getExistingDirectory(self)
        self.plainTextEdit_TrainingDataPath.setPlainText(self.training_data_path)
        self.training_image_list = self.get_image_name(self.training_data_path)
        self.listWidget_ImageName_display()

    @pyqtSlot()
    def on_pushButton_AIModelPath_4_clicked(self):
        self.testing_data_path = self.file_path.getExistingDirectory(self)
        self.plainTextEdit_TestingDataPath.setPlainText(self.testing_data_path)
        self.testing_image_list = self.get_image_name(self.testing_data_path)
        self.listWidget_ImageName_display()

    @pyqtSlot()
    def on_listWidget_ImageName_itemDoubleClicked(self):
        if self.display_type == 'Training':
            self.image_display(self.training_image_list[self.listWidget_ImageName.currentRow()])
        elif self.display_type == 'Testing':
            self.image_display(self.testing_image_list[self.listWidget_ImageName.currentRow()])
        elif self.display_type == 'All':
            self.image_display(self.all_image_list[self.listWidget_ImageName.currentRow()])

    @pyqtSlot()
    def on_pushButton_clicked(self):
        self.image_zoom_in()
        self.image_handler()

    @pyqtSlot()
    def on_pushButton_2_clicked(self):
        self.image_zoom_out()
        self.image_handler()

    @pyqtSlot()
    def on_pushButton_3_clicked(self):
        self.image_fit()
        self.image_handler()

    @staticmethod
    def get_image_name(data_path):
        image_list = []
        if isdir(data_path):
            for item in listdir(data_path):
                full_path = join(data_path, item)
                try:
                    Image.open(full_path)
                    image_list.append(full_path)
                except UnidentifiedImageError:
                    pass

            return image_list
        else:
            return []

    def listWidget_ImageName_display(self):


    def display_determine(self):
        if self.display_type == 'Training':


    def sort_determine(self):
        if self.sort_type == 'Image Type':


    def label_determine(self):
        if self.label_type == 'Without Mark':


    def image_data_sort_by_time(self, image_list):
        buf = []
        self.listWidget_ImageName.clear()
        if image_list is not None:
            for each in image_list:
                buf.append([each, strftime('%Y-%m-%d %H:%M:%S', localtime(getmtime(each)))])
            buf.sort(key=lambda x: x[1])
            return list(array(buf)[:, 0])
        else:
            return []

    def image_display(self, img):
        self.image.load(img)
        self.image_handler()

    def image_handler(self):
        image_copy = self.image
        self.pix = QPixmap.fromImage(image_copy)
        self.pix = self.pix.scaled(self.image_width, self.image_height)
        self.pix_item = QGraphicsPixmapItem(self.pix)
        self.scene.clear()
        self.scene.addItem(self.pix_item)
        self.graphicsView.setSceneRect(0, 0, self.image_width, self.image_height)
        self.graphicsView.setScene(self.scene)

    def image_zoom_in(self):
        self.image_width = self.image_width + 10
        self.image_height = self.image_height + 10

    def image_zoom_out(self):
        self.image_width = self.image_width - 10
        self.image_height = self.image_height - 10

    def image_fit(self):
        self.image_width = self.graphicsView.width() - 10
        self.image_height = self.graphicsView.height() - 10
Example #46
0
	def outFile(self):
		"""Display file dialog for output  file"""
		self.OutlEdt.clear()
		outvLayer = QFileDialog.getSaveFileName(self, "Output map",".", "ESRI Shapefile (*.shp)")
		self.OutlEdt.insert(outvLayer[0])
		return outvLayer
Example #47
0
 def database_save_mapping(self):
     filename, _ = QFileDialog.getSaveFileName(self, "Save mapping", "",
                                               "Json files (*.json)")
     store_mapping(self.model, filename)
Example #48
0
 def setDocxUrl(self):
     #重新选择输入和输出目录时,进度条设置为0,文本框的内容置空
     str = QFileDialog.getExistingDirectory(self,"选中生成docx文件所在目录",r"C:\Users\Administrator\Desktop")
     self.docxLineEdit.setText(str)
Example #49
0
 def set_path(self):
     get_directory_path = QFileDialog.getExistingDirectory(
         None, '请选择保存路径', '')
     self.lineEdit_savepath.setText(str(get_directory_path))
Example #50
0
import sys
import os
from PyQt5.QtWidgets import QApplication, QFileDialog

from events import Events
from exporthdf5 import exportEventsHDF5
from loadopenephysevents import readEventFile

if __name__ == "__main__":
    app = QApplication(sys.argv)

    fileName = QFileDialog.getOpenFileName(None, "open events file", "",
                                           "events file (*.events)")
    fileName = fileName[0]
    if (fileName == ""):
        exit(0)

    fName, fExt = os.path.splitext(fileName)

    data = readEventFile(fileName)
    events = Events(data["timestamps"], data["eventChs"], data["eventIDs"])
    exportEventsHDF5(fName + ".h5", events)
Example #51
0
 def create(self):
     filename = ""
     dialog = QFileDialog()
     dialog.setFileMode(QFileDialog.AnyFile)
     dialog.setNameFilter("ePub3 (*.epub);;All (*)")
     dialog.setWindowTitle("Create Ebook")
     dialog.setOption(QFileDialog.DontUseNativeDialog, True)
     dialog.setAcceptMode(QFileDialog.AcceptSave)
     dialog.setDirectory(self.book.source_path)
     dialog.setDefaultSuffix("epub")
     if dialog.exec_():
         filename = dialog.selectedFiles()[0]
     del dialog
     if not filename:
         return
     QApplication.setOverrideCursor(Qt.WaitCursor)
     createEpub(filename, self.book, self)
     QApplication.restoreOverrideCursor()
Example #52
0
 def button_open_range_file(self):
     fname = QFileDialog.getOpenFileName(self, 'Open Range File',
                                         os.getcwd(),
                                         "Range files (*.rrng, *.RRNG)")
     self.ui.le_rrng_fname.setText(fname[0])
Example #53
0
    def addImage(self):
        fileName = ""
        dialog = QFileDialog()
        dialog.setFileMode(QFileDialog.AnyFile)
        dialog.setNameFilter("Image Files(*.png *.jpg *.bmp *.gif);;All (*)")
        dialog.setWindowTitle("Load Image")
        dialog.setOption(QFileDialog.DontUseNativeDialog, True)
        dialog.setAcceptMode(QFileDialog.AcceptOpen)
        if dialog.exec_():
            fileName = dialog.selectedFiles()[0]
        del dialog
        if not fileName:
            return

        base = os.path.basename(fileName)
        if not os.path.exists(
                os.path.join(self.book.source_path, "images", base)):
            copy(fileName, os.path.join(self.book.source_path, "images"))
        item = QListWidgetItem()
        item.setText(Path(fileName).name)
        item.setData(
            1,
            os.path.join(self.book.source_path, "images",
                         Path(fileName).name))
        self.image_list.addItem(item)
Example #54
0
 def button_open_data_file(self):
     fname = QFileDialog.getOpenFileName(self, 'Open Pos File', os.getcwd(),
                                         "Pos files (*.pos)")
     self.ui.le_data_fname.setText(fname[0])
Example #55
0
 def selectFile(self):
     '''选取单个文件'''
     fileName, filetype = QFileDialog.getOpenFileName(
         self, "选取文件", "", "All Files (*);;")  # 设置文件扩展名过滤,注意用双分号间隔
     self.selectFileLineEdit.setText(fileName)  # 设置输入框的值
Example #56
0
 def select_dir(self):
     '''
     弹出文件对话框选择保存目录
     '''
     self.dir = QFileDialog.getExistingDirectory(
         self, '选择保存路径', (self.dir if self.dir else './'))
Example #57
0
	def chooseDir(self):
		directory = QFileDialog.getExistingDirectory(self, "选择工作路径", "./")
		self.lineEdit_4.setText(directory)
Example #58
0
    def openimage(self):
        Eng2Chi = {"green": "绿色", "blue": "蓝色", "yellow": "黄色"}
        #打开文件路径
        #设置文件扩展名过滤,注意用双分号间隔
        imgPath, imgType = QFileDialog.getOpenFileName(
            self, "打开图片", "", "*.jpg;;*.png;;*.jpeg;;*.bmp;;All Files (*)")
        print(imgPath)
        #利用qlabel显示图片
        png = QtGui.QPixmap(imgPath).scaled(self.imgLabel.width(),
                                            self.imgLabel.height())
        self.imgLabel.setPixmap(png)

        if imgPath:
            ###################识别#####################
            final_result = None
            color_index = None
            q = Predict()
            afterprocess, old = q.preprocess(imgPath)
            self.Img_preprocess = afterprocess
            colors, card_imgs = q.locate_carPlate(afterprocess, old)
            result, roi, color, divs = q.char_recogize(colors,
                                                       card_imgs)  # all list
            print("识别到了{0}个车牌".format(len(result)))
            if len(result) == 0:
                print("未能识别到车牌")
                self.colorLabel.setText("抱歉未能识别到车牌")
                self.NumLabel.setText("抱歉,未能识别到车牌")
                self.location.clear()
            else:
                for r in range(len(result)):
                    if len(result[r]) >= 7:
                        final_result = result[r]
                        color_index = r
                        findex = r

                if not final_result or len(final_result) < 7:
                    self.NumLabel.setText("抱歉,未能识别到车牌")
                    return

                print("#" * 10 + "识别结果是" + "#" * 10)
                ########车牌颜色########
                print("车牌的颜色为:" + Eng2Chi[color[color_index]])
                final_color = Eng2Chi[color[color_index]]
                if final_color == "蓝色":
                    self.colorLabel.setStyleSheet(
                        "QLabel{background-color:blue;color:white;font: 20pt;alignment:center;}"
                    )
                if final_color == "黄色":
                    self.colorLabel.setStyleSheet(
                        "QLabel{background-color:yellow;color:black;font: 20pt;alignment:center;}"
                    )
                if final_color == "绿色":
                    self.colorLabel.setStyleSheet(
                        "QLabel{background-color:green;color:white;font: 20pt;alignment:center;}"
                    )
                self.colorLabel.setText(final_color)
                ########车牌颜色########

                ########车牌号码########
                final_result.insert(2, "-")
                result = ''.join(final_result)
                print(result)
                self.NumLabel.setText(result)
                print("#" * 25)
                roi[color_index] = cv2.cvtColor(roi[color_index],
                                                cv2.COLOR_BGR2RGB)
                qimg = qimage2ndarray.array2qimage(roi[color_index])
                local_img = qimg.scaled(self.location.width(),
                                        self.location.height())
                self.location.setPixmap(QtGui.QPixmap(local_img))
                # QtImg = QtGui.QImage(roi[r].data,roi[r].shape[1],roi[r].shape[0],QtGui.QImage.Format_RGB888)
                # #显示图片到label中
                # self.location.resize(QtCore.QSize(roi[r].shape[1],roi[r].shape[0]))
                # self.location.setPixmap(QtGui.QPixmap.fromImage(QtImg))
                ########车牌号码########

                if len(final_result
                       ) >= 8 and u'\u4e00' <= final_result[0] <= u'\u9fff':
                    #保存至MYSQL数据库
                    conn, cur = self.connetSQL()
                    currenttime = datetime.datetime.now()
                    print(currenttime.strftime('%Y-%m-%d %H:%M:%S'))
                    try:
                        cur.execute(
                            "insert into plate(plate_num,plate_color,time)values(%s,%s,%s)",
                            (final_result, final_color, currenttime))
                        conn.commit()
                    except Exception as e:
                        print("expect: ", e)
                    finally:
                        cur.close()
                        conn.close()

            ###################识别#####################

            if len(divs) == 0:
                pass
            elif len(divs[0]) < 7:
                pass
            else:
                # 与上同理
                Gray1 = self.QImage2Pixmap(0, divs)
                #self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray1 = Gray1.scaled(self.div1.width(), self.div1.height())
                self.div1.setPixmap(QtGui.QPixmap.fromImage(Gray1))

                Gray2 = self.QImage2Pixmap(1, divs)
                # self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray2 = Gray2.scaled(self.div2.width(), self.div2.height())
                self.div2.setPixmap(QtGui.QPixmap.fromImage(Gray2))

                Gray3 = self.QImage2Pixmap(2, divs)
                # self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray3 = Gray3.scaled(self.div3.width(), self.div3.height())
                self.div3.setPixmap(QtGui.QPixmap.fromImage(Gray3))

                Gray4 = self.QImage2Pixmap(3, divs)
                # self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray4 = Gray4.scaled(self.div4.width(), self.div4.height())
                self.div4.setPixmap(QtGui.QPixmap.fromImage(Gray4))

                Gray5 = self.QImage2Pixmap(4, divs)
                # self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray5 = Gray5.scaled(self.div5.width(), self.div5.height())
                self.div5.setPixmap(QtGui.QPixmap.fromImage(Gray5))

                Gray6 = self.QImage2Pixmap(5, divs)
                # self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray6 = Gray6.scaled(self.div6.width(), self.div6.height())
                self.div6.setPixmap(QtGui.QPixmap.fromImage(Gray6))

                Gray7 = self.QImage2Pixmap(6, divs)
                # self.div1.resize(QtCore.QSize(divs[0][0].shape[1], divs[0][0].shape[0]))
                Gray7 = Gray7.scaled(self.div7.width(), self.div7.height())
                self.div7.setPixmap(QtGui.QPixmap.fromImage(Gray7))
Example #59
0
 def selectDir(self):
     '''选取文件夹'''
     directory = QFileDialog.getExistingDirectory(self, "选取文件夹",
                                                  "D:/pythonCode/")  # 起始路径
     self.selectDirLineEdit.setText(directory)  # 设置输入框的值
Example #60
0
def open_folder_clicked(param):
    global path_in, raw_imgs, raw_masks, merged_masks, id_masks, id_masks_initial, current_frame_index, \
        trj, cell_ids, background_id, color_list, wide_track_cell_id
    result = QFileDialog.getExistingDirectory(None, 'Select Folder', path_in)
    if len(result) == 0:
        logging.info('Canceled folder selection')
    else:
        with pg.BusyCursor():
            path_in = result
            logging.info('Selected folder: "{}"'.format(path_in))
            new_imgs = read_img_sequence(path_in,
                                         params['Raw image extension'][0])
            new_masks = read_img_sequence(
                path_in + params['Mask folder suffix'][0],
                params['Mask extension'][0])
            if len(new_imgs) == len(new_masks) > 0:
                # Clear previous data
                trj = None
                col_tuple.clear()
                col_weights.clear()
                merged_masks = None
                id_masks = None
                id_masks_initial = None
                cell_ids = []
                cell_y.clear()
                cell_x.clear()
                for cell_id in track_plots_per_cell:
                    v_raw_img.removeItem(track_plots_per_cell[cell_id])
                    # v_raw_img.removeItem(contour_plots_per_cell[cell_id])
                    pi_raw_img.removeItem(cell_ids_raw_img[cell_id])
                    pi_mask.removeItem(cell_ids_mask[cell_id])
                # contour_plots_per_cell.clear()
                # contour_data_per_frame.clear()
                wide_track_cell_id = None
                track_plots_per_cell.clear()
                track_data_per_frame.clear()
                color_list = None
                cell_color_idx.clear()
                cell_visibility.clear()
                cell_frame_presence.clear()
                cell_ids_raw_img.clear()
                cell_ids_mask.clear()
                p_cell_selection.clearChildren()
                v_raw_img.ui.histogram.gradient.restoreState(
                    v_raw_img_original_state)
                v_mask.ui.histogram.gradient.restoreState(
                    v_mask_original_state)
                # Read new data
                raw_imgs = new_imgs
                raw_masks = new_masks
                current_frame_index = 0
                background_id = -1
                v_raw_img.setImage(raw_imgs, axes={'x': 1, 'y': 0, 't': 2})
                v_raw_img.setCurrentIndex(current_frame_index)
                pi_raw_img.setWindowTitle(str(current_frame_index))
                v_mask.setImage(raw_masks, axes={'x': 1, 'y': 0, 't': 2})
                v_mask.setCurrentIndex(current_frame_index)
                b_cell_tracking.setEnabled(True)
                b_save_selected.setEnabled(False)
                b_select_all.setEnabled(False)
                b_select_none.setEnabled(False)
                b_select_complete.setEnabled(False)
                # win.setWindowTitle('Cell Tracking ({})'.format(path_in))  # If you want to know which dataset you opened, pressing the "Open Folder" button will take you to the current dataset
            else:
                if len(new_imgs) == len(new_masks):
                    pg.Qt.QtGui.QMessageBox.error(
                        b_save_selected, 'Data reading failed',
                        'Failed to read data from path "{}"'.format(path_in))
                else:
                    pg.Qt.QtGui.QMessageBox.error(
                        b_save_selected, 'Data reading failed',
                        'The mask and raw image sequences have different lengths'
                    )
                return