Ejemplo n.º 1
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()
Ejemplo n.º 2
0
 def setGitDirectory(self):
     gitRepo = QFileDialog.getExistingDirectory(self, "Select directory...", os.path.expanduser("~"))
     if not os.path.isdir(gitRepo):
         pass
     else:
         settings.setValue("settings/GitRepo", gitRepo)
         settings.sync()
Ejemplo n.º 3
0
    def onOpenImageDir(self):
        self.cbar.clearContours()
        self.viewer.clearRects()
        self.viewer.clearPolygons()

        idir = self.imageDir.text()
        ofile = self.dataFile.text()
        if isdir(idir):
            path = dirname(idir)
        elif isfile(ofile):
            path = dirname(ofile)
        else:
            path = expanduser("~")

        # TODO use getOpenFileNames instead
        idir = QFileDialog.getExistingDirectory(self, "Select an image directory", path)
        # cancel button
        if not idir:
            return

        self.imageDir.setText(idir)

        scanner = FileScanner(self.structType.currentText(), idir)
        self._files = scanner()

        if not self._files:
            QMessageBox.warning(self, "Error", "No files found")
            return

        try:
            self._dimUpdate(self._files[0].file)
            self._initialImage()
        except IOError as e:
            pass
Ejemplo n.º 4
0
def saveScreenshot(pixmap):
    global settings
    global soundEffect
    global savePathValue

    soundEffect.play()

    fileName = "%s%s.png" % (_("DeepinScreenshot"),
                             time.strftime("%Y%m%d%H%M%S", time.localtime()))
    save_op = settings.getOption("save", "save_op")
    save_op_index = int(save_op)

    absSavePath = os.path.abspath(savePathValue)
    if savePathValue and os.path.exists(os.path.dirname(absSavePath)):
        savePixmap(pixmap, absSavePath)
    else:
        saveDir = ""
        copy = False
        if save_op_index == 0: #saveId == "save_to_desktop":
            saveDir = QStandardPaths.writableLocation(QStandardPaths.DesktopLocation)
        elif save_op_index == 1: #saveId == "auto_save" :
            saveDir = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
        elif save_op_index == 2: #saveId == "save_to_dir":
            saveDir = QFileDialog.getExistingDirectory()
        elif save_op_index == 4: #saveId == "auto_save_ClipBoard":
            copy = True
            saveDir = QStandardPaths.writableLocation(QStandardPaths.PicturesLocation)
        else: copy = True

        if copy: copyPixmap(pixmap)
        if saveDir: savePixmap(pixmap, os.path.join(saveDir, fileName))
Ejemplo n.º 5
0
    def source_activated(self):
        """User chooses source device/directory."""

        # get source path from combobox
        source = self.cmb_source.currentText()

        if source == SelectDirString:
            # user wants to source from a directory, choose with a file dialog
            dirname = QFileDialog.getExistingDirectory(self, 'Select a source directory:',
                                                       osp.expanduser('~'),
                                                       QFileDialog.ShowDirsOnly)
            self.source = dirname
            if dirname not in SourcePaths:
                SourcePaths.append(dirname)
            self.populate_cmb_source()
            index = self.cmb_source.findText(dirname, Qt.MatchFixedString)
            if index >= 0:
                self.cmb_source.setCurrentIndex(index)
        else:
            self.source = source

        # check that source is good
        if self.source:
            if not self.good_source(self.source):
                self.warn("Path '%s' is a bad source" % self.source)
                self.source = None

        self.check_copy_disabled()
Ejemplo n.º 6
0
    def connect_ui(self):
        self.cancelButton.pressed.connect(lambda: self.reject())
        self.acceptButton.pressed.connect(lambda: self.save())

        #Emulation
        self.addPathButton.pressed.connect(lambda: self.pathList.addItem(QFileDialog.getExistingDirectory(self, 'Add ROM directory', QDir.homePath(), QFileDialog.ShowDirsOnly)))
        self.removePathButton.pressed.connect(lambda: self.pathList.takeItem(self.pathList.row(self.pathList.selectedItems()[0])))
Ejemplo n.º 7
0
 def add_action(self):
     new_folder = QFileDialog.getExistingDirectory(parent=self, caption='Add Folder', options=QFileDialog.ShowDirsOnly, directory=os.path.expandvars('~'))
     if new_folder:
         if new_folder in self._removes:
             self._removes.remove(new_folder)
         self._adds.add(new_folder)
         self.add_path_row(new_folder, False)
 def set_path(self):
     """
     Method to set a path for storage of the results using a file dialog
     :return: selected file path
     """
     return str(QFileDialog.getExistingDirectory(QFileDialog(), 'Select storage path',
                                         './resources/configuration_files/'))
Ejemplo n.º 9
0
def ask_folder(caption, parent=None, starting_path=''):
    chosen_path = QFileDialog.getExistingDirectory(
            parent,
            caption,
            starting_path
        )
    return chosen_path
 def selectCacheDir(self):
     selected_dir = QFileDialog.getExistingDirectory(self.settings, self.tr("Open Directory"), "/",
                                                     QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
     if not selected_dir == '':
         if not selected_dir == self.settings.cacheDirPath.text():
             self.settings.cacheDirPath.setText(selected_dir)
             self.markChanged()
Ejemplo n.º 11
0
 def showDialog(self):
     ''' select directory box '''
     self.dirName = str(QFileDialog.getExistingDirectory(self, "Select Directory"))        
     if self.dirName:
         os.chdir(self.dirName)
         self.dirLine.setText(self.dirName)
         self.showFileList()
Ejemplo n.º 12
0
    def on_pbBrowse_pressed(self):
        """Handler of click on "Browse" button. Explores FS for search directory path
        """
        path = QFileDialog.getExistingDirectory(self, self.tr("Search path"), self.cbPath.currentText())

        if path:
            self.cbPath.setEditText(path)
Ejemplo n.º 13
0
 def slotBrowseWorkFolder(self):
     """
         Browse work folder button fires this function.
     """
     directory = QFileDialog.getExistingDirectory(self, "")
     if directory:
         self.lineWorkFolder.setText(directory)
Ejemplo n.º 14
0
    def _exportAllObjectMeshes(self):
        """
        Export all objects in the project as separate .obj files, stored to a user-specified directory.
        """
        mst = self.topLevelOperatorView.MST.value
        if not list(mst.object_lut.keys()):
            QMessageBox.critical(self, "Can't Export", "You have no saved objets, so there are no meshes to export.")
            return
        
        recent_dir = PreferencesManager().get( 'carving', 'recent export mesh directory' )
        if recent_dir is None:
            defaultPath = os.path.join( os.path.expanduser('~') )
        else:
            defaultPath = os.path.join( recent_dir )
        export_dir = QFileDialog.getExistingDirectory( self, 
                                                       "Select export directory for mesh files",
                                                       defaultPath)
        if not export_dir:
            return
        export_dir = str(export_dir)
        PreferencesManager().set( 'carving', 'recent export mesh directory', export_dir )

        # Get the list of all object names
        object_names = []
        obj_filepaths = []
        for object_name in list(mst.object_lut.keys()):
            object_names.append( object_name )
            obj_filepaths.append( os.path.join( export_dir, "{}.obj".format( object_name ) ) )
        
        if object_names:
            self._exportMeshes( object_names, obj_filepaths )
Ejemplo n.º 15
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()
Ejemplo n.º 16
0
 def slotBrowseReleaseFiles(self):
     """
         Browse release files button fires this function.
     """
     directory = QFileDialog.getExistingDirectory(self, "")
     if directory:
         self.lineReleaseFiles.setText(directory)
Ejemplo n.º 17
0
    def browse_dialog(self, args):
        widget, groupbox, directory = args
        dialog = QFileDialog()
        if directory:
            dialog.setFileMode(QFileDialog.Directory)
            path = dialog.getExistingDirectory(
                self, groupbox.title(), widget.text(), QFileDialog.ShowDirsOnly)
        else:
            dialog.setFileMode(QFileDialog.ExistingFile)
            path, _ = dialog.getOpenFileName(
                self, groupbox.title(), widget.text(),
                "%s (*%s);;All files (*)" % (groupbox.title(), DLL_FILTER))

        if not path:
            return

        widget.setText(path)
        if widget == self.pathLibrary:
            self.parent.worker.quit()
            if not self.parent.worker.core.get_handle():
                self.parent.worker.init(path)
                if self.parent.worker.core.get_handle():
                    self.core = self.parent.worker.core
                    self.set_core()
                    self.set_video()
                    self.parent.window_size_triggered(self.get_size_safe())
                    self.parent.state_changed.emit((True, False, False, False))
        elif widget == self.pathPlugins:
            self.parent.worker.plugins_shutdown()
            self.parent.worker.plugins_unload()
            self.parent.worker.plugins_load(path)
            self.parent.worker.plugins_startup()
            self.set_plugins()
Ejemplo n.º 18
0
 def setExistingDirectory(self):    
     options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
     directory = QFileDialog.getExistingDirectory(self,
             "QFileDialog.getExistingDirectory()",
             self.directoryLabel.text(), options=options)
     if directory:
         self.directoryLabel.setText(directory)
Ejemplo n.º 19
0
 def choose_directory(self, arg=False):
     dir_files = ''
     if arg is not False:
         directory = [arg][0]
         dir_files = os.listdir(directory)
     else:
         directory = QFileDialog.getExistingDirectory(directory=os.getenv('HOME'), caption="Open directory with tracks")
         if directory != '':
             dir_files = os.listdir(directory)
     count = len(dir_files)
     start_all = time.time()
     for track in dir_files:
         is_audio = False
         is_video = False
         for a in audio_files:
             if track.lower().endswith(a):
                 is_audio = True
                 break
         for v in video_files:
             if track.lower().endswith(v):
                 is_video = True
                 break
         if is_audio:
             fullpath = os.path.realpath(directory) + "/" + track
             queue.put(fullpath)
         # # Adds it directly, bypassing threading (doesn't play nice)
         elif is_video:
             fullpath = os.path.realpath(directory) + "/" + track
             self.process_track(fullpath)
         # Track was no track at all!
         else:
             count -= 1
     self.start_working(start_all, count)
    def selectOutputFile(self):
        folderTmp = QFileDialog.getExistingDirectory(self.dlg, "Select output folder ", self.folderName)

        if folderTmp != "":
            self.folderName = folderTmp

        self.dlg.lineEdit.setText(self.folderName);
Ejemplo n.º 21
0
 def browse(self):
     f = QFileDialog.getExistingDirectory(self.window(), 
                                         self.tr("Choose the Maps Folder"),
                                         self.mDirectoryEdit.text())
     if (not f.isEmpty()):
         prefs = preferences.Preferences.instance()
         prefs.setMapsDirectory(f)
Ejemplo n.º 22
0
 def getPath(self):
     path = _QFileDialog.getExistingDirectory(self)
     
     if path != '':
         self.path = path + '/'
         self.ui.lineEditPath.setText(self.path)
         self.changeFilename()
Ejemplo n.º 23
0
			def from_dir():
				path = QFileDialog.getExistingDirectory(self, "Choose a directory containing your galleries")
				if not path:
					return
				msg_box.close()
				app_constants.OVERRIDE_SUBFOLDER_AS_GALLERY = True
				self.gallery_populate(path, True)
Ejemplo n.º 24
0
    def _browse(self):
        new_download_dir = QFileDialog.getExistingDirectory(self, 'Select download directory', self._download_dir)
        if not new_download_dir:
            return

        self._download_dir = new_download_dir
        self._path_edit.setText(new_download_dir)
Ejemplo n.º 25
0
    def _chooseDirectory(self):
        # Find the directory of the most recently opened image file
        mostRecentStackDirectory = PreferencesManager().get( 'DataSelection', 'recent stack directory' )
        if mostRecentStackDirectory is not None:
            defaultDirectory = os.path.split(mostRecentStackDirectory)[0]
        else:
            defaultDirectory = os.path.expanduser('~')

        options = QFileDialog.Options(QFileDialog.ShowDirsOnly)
        if ilastik.config.cfg.getboolean("ilastik", "debug"):
            options |= QFileDialog.DontUseNativeDialog

        # Launch the "Open File" dialog
        directory = QFileDialog.getExistingDirectory( 
                     self, "Image Stack Directory", defaultDirectory, options=options )

        if not directory:
            # User cancelled
            return

        PreferencesManager().set('DataSelection', 'recent stack directory', directory)

        self.directoryEdit.setText( directory )
        try:
            globstring = self._getGlobString(directory)
        except StackFileSelectionWidget.DetermineStackError as e:
            QMessageBox.warning(self, "Invalid selection", str(e))
        if globstring:
            self.patternEdit.setText( globstring )
            self._applyPattern()
Ejemplo n.º 26
0
    def savePic(self):
        densityPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'闪电密度空间分布.tif'])

        dayPic = ''.join([cwd,u'/bulletinTemp/',self.in_parameters[u'datetime'],u'/',
            self.in_parameters[u'target_area'],'.gdb',u'/',self.in_parameters[u'datetime'],
            self.in_parameters[u'target_area'],u'地闪雷暴日空间分布.tif'])

        directory = QFileDialog.getExistingDirectory(self,u'请选择图片保存位置',
                                                     u'E:/Documents/工作/雷电公报',
                                    QFileDialog.ShowDirsOnly|QFileDialog.DontResolveSymlinks)

        dest_density = os.path.join(directory,os.path.basename(densityPic))
        dest_day = os.path.join(directory,os.path.basename(dayPic))

        if os.path.isfile(dest_day) or os.path.isfile(dest_density):
            message = u"文件已经存在!"
            msgBox = QMessageBox()
            msgBox.setText(message)
            msgBox.setIcon(QMessageBox.Information)
            icon = QIcon()
            icon.addPixmap(QPixmap("./resource/weather-thunder.png"), QIcon.Normal, QIcon.Off)
            msgBox.setWindowIcon(icon)
            msgBox.setWindowTitle(" ")
            msgBox.exec_()
            return

        move(dayPic,directory)
        move(densityPic,directory)
Ejemplo n.º 27
0
    def retrieveCharacters(self) -> bool:
        """ Retrieve the character set

            The character set is a list of files with the extention chr
            in the directory that will be selected by the user in this method

            Returns:
                bool : True is the user selected a source directory
        """

        # Retrieve the directory
        fileDirectory = os.path.join(dataDir, "Chapter 3 - Distance Metrics")
        dir = QFileDialog.getExistingDirectory(self, "Open Directory", fileDirectory, QFileDialog.ShowDirsOnly
                                               | QFileDialog.DontResolveSymlinks)

        if dir == "":
            return False

        # Retrieve all the files in the directory
        charFiles = FileUtiles.GetAllFilesInFolder(dir, False, "chr")

        # Show the files
        for charFile in charFiles:
            charFile = dir + '/' + charFile
            self.mainItem.addCharacter(charFile)
        self.graphicsScene.update()
        return 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
Ejemplo n.º 29
0
 def openBuildPathFileDialog(self):
     brows = QFileDialog()
     self.getPath = brows.getExistingDirectory(self,
                                               "Select Directory",
                                               expanduser("~"),
                                               QFileDialog.ShowDirsOnly)
     self.buildLocationEdit.setText(self.getPath)
Ejemplo n.º 30
0
    def choose_directory(self, folder, override=False):
        """
        Open the file dialog to allow the user to select a path for
        the given folder.

        :param folder:
        :param override: set to True if this is for a profile
            dir-override
        :return:
        """

        # fixme: this doesn't seem to actually show the current folder if there
        # is one...maybe that's a Qt bug, though. Or maybe it's because of the
        # hidden folder in the path?

        start = self._selected_profile.diroverride(folder) if override else self.paths[folder]

        # noinspection PyTypeChecker
        chosen = QFileDialog.getExistingDirectory(self,
                                                  "Select directory",
                                                  start or "")

        if check_path(chosen):

            if override:
                self.override_boxes[folder].setText(chosen)
            else:
                self.path_boxes[folder].setText(chosen)
                if folder in self.indicator_labels.keys():
                    self.indicator_labels[folder].setVisible(False)
Ejemplo n.º 31
0
    def save_report(self):

        try:
            options = QFileDialog.DontResolveSymlinks | QFileDialog.ShowDirsOnly
            directory = QFileDialog.getExistingDirectory(self,
                                                         "",
                                                         "",
                                                         options=options)

            all = self.sum_all_data()

            if directory:

                workbook = xlsxwriter.Workbook('{}/report_{}.xlsx'.format(
                    directory,
                    datetime.datetime.now().strftime("%Y%m%d_%H%M%S")))
                worksheet = workbook.add_worksheet()
                bold = workbook.add_format({
                    'bold': True,
                    'bg_color': '#CCCCCC',
                    'border': 1
                })
                red = workbook.add_format({'bg_color': '#FFC7CE', 'border': 1})
                green = workbook.add_format({
                    'bg_color': '#e5fbe5',
                    'border': 1
                })

                worksheet.write(0, 1, "Сводный отчет за период")

                worksheet.set_column('B:E', 25)

                worksheet.write('B2', self.column_name_table_records[0], bold)
                worksheet.write('C2', self.column_name_table_records[1], bold)
                worksheet.write('D2', self.column_name_table_records[2], bold)

                i = 2
                for row in all:
                    bgcolor = green if row[0] == 1 else red

                    if row[0] == 1:
                        for row2 in self.data_incomes:
                            if row[1][3] == row2[0]:
                                worksheet.write(i, 2, row2[1],
                                                bgcolor)  # Статья

                    elif row[0] == 2:
                        for row2 in self.data_costs:
                            if row[1][3] == row2[0]:
                                worksheet.write(i, 2, row2[1],
                                                bgcolor)  # Статья

                    worksheet.write(i, 1,
                                    self.unix_time_to_datetime_utc(row[1][1]),
                                    bgcolor)  # Дата

                    worksheet.write_number(i, 3, row[1][2] / 100,
                                           bgcolor)  # Сумма
                    i += 1

                workbook.close()

        except Exception as err:
            QMessageBox.warning(self, 'Error', ' Error save: {}'.format(err))
Ejemplo n.º 32
0
 def outputDialog(self):
     fname = QFileDialog.getExistingDirectory(self, "Open Folder", "C:/Users")
     self.outputEdit.setText(fname)
Ejemplo n.º 33
0
	def selectProjectFolder(self):
		folderName = QFileDialog.getExistingDirectory(None, "Select project folder","./")
		self.projectFolderLineEdit.setText(folderName)

		if os.path.isdir(folderName) == False:
			os.system("mkdir "+folderName)
Ejemplo n.º 34
0
 def Button4_clicked(self):
     file_path = QFileDialog.getExistingDirectory(self, "选择对齐后保存文件的路径", "/")
     self.lineEdit_4.setText(file_path)
     self.Aligned_blendshapes_path = file_path
Ejemplo n.º 35
0
 def Button2_clicked(self):
     file_path = QFileDialog.getExistingDirectory(self, "选择Blendshape路径",
                                                  "/")
     self.lineEdit_2.setText(file_path)
     self.blendshapes_path = file_path
Ejemplo n.º 36
0
    def TOMsExportAtlas(self, printProposalObject):

        # TH (180608): Export function to deal with atlases

        settings = QSettings()
        format = self.dialogui.comboBox_fileformat.itemData(self.dialogui.comboBox_fileformat.currentIndex())

        # TH (180608): Check to see whether or not the Composer is an Atlas
        currPrintLayout = self.layoutView
        currLayoutAtlas = currPrintLayout.atlas()

        success = False

        # https://gis.stackexchange.com/questions/77848/programmatically-load-composer-from-template-and-generate-atlas-using-pyqgis?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

        self.TOMsSetAtlasValues(currPrintLayout)

        currRevisionDate = self.proposalsManager.date()

        # get the map tiles that are affected by the Proposal
        # self.getProposalTileList(currProposalID, currRevisionDate)

        proposalTileDictionaryForDate = printProposalObject.getProposalTileDictionaryForDate(currRevisionDate)
        """self.tileSet = set(
            proposalTileDictionaryForDate)"""  # TODO: Change around use of tileSet - also might be good to have a current proposal as an object in proposalManager...

        # Now check which tiles to use
        self.tilesToPrint = self.TOMsChooseTiles(proposalTileDictionaryForDate)

        if len(self.tilesToPrint) == 0:
            return

        # get the output location
        dirName = QFileDialog.getExistingDirectory(
            self.iface.mainWindow(),
            self.tr("Export Composition"),
            settings.value("/instantprint/lastdir", ""),
            QFileDialog.ShowDirsOnly
        )
        if not dirName:
            return

        settings.setValue("/instantprint/lastdir", dirName)

        tileIDList = ""
        firstTile = True
        for tile in self.tilesToPrint:
            if firstTile:
                tileIDList = str(tile.attribute("id"))
                firstTile = False
            else:
                tileIDList = tileIDList + ',' + str(tile.attribute("id"))

        currLayoutAtlas.setFilterFeatures(True)
        currLayoutAtlas.setFilterExpression(' "id" in ({tileList})'.format(tileList=tileIDList))

        composerRevisionNr = currPrintLayout.itemById('revisionNr')
        composerEffectiveDate = currPrintLayout.itemById('effectiveDate')
        composerProposalStatus = currPrintLayout.itemById('proposalStatus')

        if composerProposalStatus is not None:
            composerProposalStatus.setText(self.proposalForPrintingStatusText)
        else:
            QMessageBox.warning(self.iface.mainWindow(), self.tr("Missing label in Layout"),
                                self.tr("Missing label 'proposalStatus'"))

        composerPrintTypeDetails = currPrintLayout.itemById('printTypeDetails')
        if composerPrintTypeDetails is not None:
            composerPrintTypeDetails.setText(self.proposalPrintTypeDetails)
        else:
            QMessageBox.warning(self.iface.mainWindow(), self.tr("Missing label in Layout"),
                                self.tr("Missing label 'printTypeDetails'"))

            # currProposalTitle, currProposalOpenDate = self.getProposalTitle(currProposalID)
            #printProposal = printProposalObject
        currProposalTitle = printProposalObject.getProposalTitle()
        currProposalOpenDate = printProposalObject.getProposalOpenDate()

        if printProposalObject.thisProposalNr == 0:
            currProposalTitle = "CurrentRestrictions_({date})".format(
                date=self.proposalsManager.date().toString('yyyyMMMdd'))

        QgsMessageLog.logMessage("In TOMsExportAtlas. Now printing " + str(currLayoutAtlas.count()) + " items ....",
                                 tag="TOMs panel")

        currLayoutAtlas.setEnabled(True)
        currLayoutAtlas.updateFeatures()
        currLayoutAtlas.beginRender()

        altasFeatureFound = currLayoutAtlas.first()

        while altasFeatureFound:

            currTileNr = int(currLayoutAtlas.nameForPage(currLayoutAtlas.currentFeatureNumber()))

            currLayoutAtlas.refreshCurrentFeature()

            #tileWithDetails = self.tileFromTileSet(currTileNr)
            tileWithDetails = proposalTileDictionaryForDate[currTileNr]

            if tileWithDetails == None:
                QgsMessageLog.logMessage("In TOMsExportAtlas. Tile with details not found ....", tag="TOMs panel")
                QMessageBox.warning(self.iface.mainWindow(), self.tr("Print Failed"),
                                    self.tr("Could not find details for " + str(currTileNr)))
                break

            QgsMessageLog.logMessage("In TOMsExportAtlas. tile nr: " + str(currTileNr) + " RevisionNr: " + str(
                tileWithDetails["RevisionNr"]) + " RevisionDate: " + str(tileWithDetails["LastRevisionDate"]),
                                     tag="TOMs panel")

            if self.proposalForPrintingStatusText == "CONFIRMED":
                composerRevisionNr.setText(str(tileWithDetails["RevisionNr"]))
                composerEffectiveDate.setText(
                    '{date}'.format(date=tileWithDetails["LastRevisionDate"].toString('dd-MMM-yyyy')))
            else:
                composerRevisionNr.setText(str(tileWithDetails["RevisionNr"] + 1))
                # For the Proposal, use the current view date
                composerEffectiveDate.setText(
                    '{date}'.format(date=self.openDateForPrintProposal.toString('dd-MMM-yyyy')))

            filename = currProposalTitle + "_" + str(
                currTileNr) + "." + self.dialogui.comboBox_fileformat.currentText().lower()
            outputFile = os.path.join(dirName, filename)

            exporter = QgsLayoutExporter(currLayoutAtlas.layout())

            if self.dialogui.comboBox_fileformat.currentText().lower() == u"pdf":
                result = exporter.exportToPdf(outputFile, QgsLayoutExporter.PdfExportSettings())
                # success = currLayoutAtlas.composition().exportAsPDF(outputFile)
            else:
                result = exporter.exportToImage(outputFile, 'png', QgsLayoutExporter.ImageExportSettings())
                """image = currLayoutAtlas.composition().printPageAsRaster(0)
                if not image.isNull():
                    success = image.save(outputFile)"""

            if result != QgsLayoutExporter.Success:
                QMessageBox.warning(self.iface.mainWindow(), self.tr("Print Failed"),
                                    self.tr("Failed to print " + exporter.errorFile()))
                break

            altasFeatureFound = currLayoutAtlas.next()

        currLayoutAtlas.endRender()

        QMessageBox.information(self.iface.mainWindow(), "Information",
                                ("Printing completed"))
Ejemplo n.º 37
0
 def onOpenClicked(self):
     file = str(QFileDialog.getExistingDirectory(self, "Choose Directory"))
     self.lnEdit.setText(file)
Ejemplo n.º 38
0
 def search_for_files(self):
     self.folder = str(
         QFileDialog.getExistingDirectory(self.window, "Select Directory"))
     self.ui.directory.setText(self.folder)
Ejemplo n.º 39
0
    def getInstallFolder(self):
        folder = QFileDialog.getExistingDirectory(self, 'Mod folder location', '', QFileDialog.ShowDirsOnly)

        if folder:
            self.installFolderLineEdit.setText(str(folder))
            get_config().set("PATHS", "installFolder", str(folder))
Ejemplo n.º 40
0
 def openFileDialog(self):
     foldername = QFileDialog.getExistingDirectory(self)
     if foldername:
         self.foldername = foldername
Ejemplo n.º 41
0
 def opendir(self):
     self.dir = QFileDialog.getExistingDirectory()
     # if self.dir == '':
     #    self.dir = 'default'
     self.lineEdit.setText(self.dir)
Ejemplo n.º 42
0
 def manual_cloud_folder_entry(self):
     cloud_folder = QFileDialog.getExistingDirectory(
         None, 'Select a folder:', None, QFileDialog.ShowDirsOnly)
     self.cloud_folder_line.setText(cloud_folder)
     self.cloud_folder_list.insertItem(0, cloud_folder)
     self.cloud_folder_list.setCurrentItem(self.cloud_folder_list.item(0))
Ejemplo n.º 43
0
class ViewGraph(QMainWindow, ui.Ui_MainWindow):
    resized = QtCore.pyqtSignal()

    def __init__(self, config, main=None) -> None:

        super().__init__()
        self.setupUi(self)

        self.main_window = main
        self.iter_value = config.iter_value
        self.max_start_search = config.max_start_search
        self.max_end_search = config.max_end_search
        self.min_start_search = config.min_start_search
        self.min_end_search = config.min_end_search
        self.max_step_iter = config.max_step_iter
        self.default_step_iter = config.default_step_iter
        self.bandwidths = config.bandwidths
        self.lineEditMaxStart.setText(str(self.max_start_search))
        self.lineEditMaxEnd.setText(str(self.max_end_search))
        self.lineEditMinStart.setText(str(self.min_start_search))
        self.lineEditMinEnd.setText(str(self.min_end_search))
        self.edit_max_start_changed_event = self.lineEditMaxStart.returnPressed
        self.edit_max_end_changed_event = self.lineEditMaxEnd.returnPressed
        self.edit_min_start_changed_event = self.lineEditMinStart.returnPressed
        self.edit_min_end_changed_event = self.lineEditMinEnd.returnPressed

        self.progressBar.setMaximum(100)
        self.listBandwidths.addItems(
            ['%s' % b for b in self.bandwidths]
        )
        self.bandwidths_clicked_event = self.listBandwidths.itemClicked
        self.range_search_maxmums = pg.LinearRegionItem(
            [self.max_start_search, self.max_end_search])
        self.range_search_maxmums.setBrush(
            QtGui.QBrush(QtGui.QColor(0, 0, 255, 50))
        )
        self.maximums_region_changed_event = self.range_search_maxmums.sigRegionChangeFinished

        self.range_search_minimums = pg.LinearRegionItem(
            [self.min_start_search, self.min_end_search]
        )
        self.range_search_minimums.setBrush(
            QtGui.QBrush(QtGui.QColor(0, 0, 50, 50))
        )
        self.minimums_region_changed_event = self.range_search_minimums.sigRegionChangeFinished

        open_file_button = QAction(QIcon('open.png'), 'Open', self)
        open_file_button.setShortcut('Ctrl+O')
        open_file_button.setStatusTip('Open Source File')
        self.menu_open_file_event = open_file_button.triggered

        save_file_button = QAction(QIcon('save.png'), 'Save', self)
        save_file_button.setShortcut('Ctrl+S')
        save_file_button.setStatusTip('Save Filtered Data')
        self.menu_save_file_event = save_file_button.triggered

        close_file_button = QAction(QIcon('close.png'), 'Close', self)
        close_file_button.setShortcut('Ctrl+X')
        close_file_button.setStatusTip('Close')
        self.menu_close_file_event = close_file_button.triggered

        self.file_dialog_open = QFileDialog()
        self.file_dialog_open.setFileMode(0)
        self.file_dialog_save = QFileDialog()
        self.file_dialog_save.setFileMode(4)

        self.open_clicked_event = self.buttonOpen.clicked
        self.add_clicked_event = self.buttonAdd.clicked
        self.save_clicked_event = self.buttonSave.clicked
        self.toggle_visible_regions_event = self.buttonVisibleRegion.clicked

        self.slider1.setMinimum(0)
        self.slider1.setMaximum(self.max_step_iter)
        self.slider1.setValue(self.default_step_iter)
        self.value_changed_event = self.slider1.valueChanged

        menu_bar = self.menuBar()
        file_menu = menu_bar.addMenu('&File')
        file_menu.addAction(open_file_button)
        file_menu.addAction(save_file_button)
        file_menu.addAction(close_file_button)

    def resizeEvent(self, event):
        self.resized.emit()
        return super(ViewGraph, self).resizeEvent(event)

    def show_graphic_filtered(
            self,
            dict_data,
            showed_maxs,
            showed_mins,
            tick_times,
            total_count
    ) -> bool:
        """
        Draw plot of filtered data.
        Returns - True if ok.
        """
        if total_count == 0:
            return False

        delta = 0
        count = 0
        for time_stamp, row in dict_data.items():
            delta -= self.iter_value  # + last_max_value
            y = row + delta
            graph_item = self.graph.getPlotItem().dataItems[count]
            # just set curves for draggable points for move it this curve
            showed_maxs[time_stamp].set_curve(tick_times, y)
            showed_mins[time_stamp].set_curve(tick_times, y)
            graph_item.setData(tick_times,  y,)
            count += 1

        return True

    def show_range_extremums(self, total_count) -> bool:
        """
        Draw regions where will search maximums and minimums of curves.
        Returns - True if ok.
        """
        # logger.debug("start show graph extrem")
        if total_count == 0:
            return False
        self.range_search_maxmums.setRegion([
            float(self.lineEditMaxStart.text()),
            float(self.lineEditMaxEnd.text())
        ])
        self.range_search_minimums.setRegion([
            float(self.lineEditMinStart.text()),
            float(self.lineEditMinEnd.text())
        ])

        return True

    def reshow_extremums(
            self,
            dict_data,
            showed_extremums,
            params
    ) -> bool:
        """
        Draw point of maximums and minimums of curves in showed regions.
        Returns - True if ok.
        """
        delta = 0
        for time_stamp, row in dict_data.items():
            delta -= self.iter_value  # + last_max_value
            time_extremum = row[0]
            value_extremum = row[1] + delta
            showed_extremum = showed_extremums[time_stamp]
            # set model for save value of point when user change it manually
            showed_extremum.model_params = params + (time_stamp,)
            showed_extremum.setData(
                pos=np.array([[time_extremum, value_extremum]])
                )

        return True

    def show_progress_bar(self):
        """Show progress bar and hide section of bandwidths."""
        self.listBandwidths.setHidden(1)
        self.progressBar.setValue(0)
        self.progressBar.setProperty('visible', 1)

    def hide_progress_bar(self):
        """Hide progress bar and show section of bandwidths."""
        self.progressBar.setValue(0)
        self.progressBar.setProperty('visible', 0)
        self.listBandwidths.setHidden(0)

    def is_graph_empty(self):
        """Check is Graph empty."""
        if not self.graph.getPlotItem().dataItems:
            return True
        return False

    def set_progress_value(self, value):
        """Set value of progress of process."""
        self.progressBar.setValue(value)
        QApplication.processEvents()

    def add_ranges_extremums(self):
        """Add regions for search extremums."""
        self.graph.addItem(self.range_search_maxmums)
        self.graph.addItem(self.range_search_minimums)
        pass

    def create_graph(self, time_stamp):
        """Create new plot for new curve."""
        self.graph.plot(
            name=time_stamp
        )

    def get_ranges_extremums(self):
        """Get values of bounds of regions for search extremums."""
        max_search_range = [round(x, 4) for x in self.range_search_maxmums.getRegion()]
        min_search_range = [round(x, 4) for x in self.range_search_minimums.getRegion()]
        return max_search_range, min_search_range

    def add_point_extremums(self, time_stamp):
        """Add new draggable points to the main graph."""

        from points import DraggablePoint

        showed_max = DraggablePoint()
        showed_max.controller = self.main_window.controller
        showed_max.setData(
            pos=np.array([[0, 0]]),
            name='max_%s' % time_stamp,
            symbol='o',
            pen=pen2,
            symbolSize=10,
            symbolBrush='r'
        )
        self.graph.addItem(showed_max)

        showed_min = DraggablePoint()
        showed_min.controller = self.main_window.controller
        showed_min.setData(
            pos=np.array([[0, 0]]),
            name='max_%s' % time_stamp,
            symbol='o',
            pen=pen2,
            symbolSize=1,
            symbolBrush='b'
        )
        self.graph.addItem(showed_min)

        return showed_max, showed_min

    def get_source_file_name(self):
        """Get name of source file."""
        return self.file_dialog_open.getOpenFileName(
            self,
            'Open source file',
            './')[0]

    def get_target_file_name(self):
        """Get name of target file."""
        return self.file_dialog_save.getExistingDirectory(
            self,
            'Save filtered data',
            './')
Ejemplo n.º 44
0
 def _result_dir_dialog(self):
     directory = str(QFileDialog.getExistingDirectory())
     self.resultDirectoryLineEdit.setText('{}'.format(directory))
Ejemplo n.º 45
0
def get_directory():
    directory = QFileDialog.getExistingDirectory(
        None, "Choose Directory", QDir.homePath(),
        QFileDialog.ShowDirsOnly | QFileDialog.DontResolveSymlinks)
    return directory
Ejemplo n.º 46
0
 def select_dest_folder(self, prompt):
     flags = QFileDialog.ShowDirsOnly
     return QFileDialog.getExistingDirectory(self.resultWindow, prompt, "", flags)
Ejemplo n.º 47
0
 def button_pix4D_clicked(self):
     self.pix4D = QFileDialog.getExistingDirectory(self, "Select the pix4D project folder")
     self.pix4D = Path(self.pix4D)
    def __init__(self, muted=False, save_frames=False, master=None):
        QtWidgets.QMainWindow.__init__(self, master)
        self.setWindowIcon(QIcon("icons/app.svg"))
        self.title = "Bilkent Video Annotation Tool"

        self.muted = muted
        self.save_frames = save_frames

        self.setWindowTitle(self.title)
        options = QFileDialog.Options()
        options |= QFileDialog.ShowDirsOnly
        options |= QFileDialog.Directory

        # options |= QFileDialog.DontUseNativeDialog

        supported_formats = [
            ".mp3", ".mp4", ".avi", ".wmv", ".mp4", ".mov", ".ogg", ".wav",
            ".ogm"
        ]

        self.video_paths = []
        while len(self.video_paths) == 0:
            videos_dir = str(
                QFileDialog.getExistingDirectory(self,
                                                 "Select Videos Directory",
                                                 options=options))
            self.video_paths = []
            for fmt in supported_formats:
                self.video_paths += [
                    f for f in glob.glob(videos_dir + "**/*" + fmt,
                                         recursive=False)
                ]
            print(self.video_paths)

            if len(self.video_paths) == 0 or len(videos_dir) == 0:
                QtWidgets.QMessageBox.question(
                    self, 'No videos exist',
                    "Please select a directory containing videos.",
                    QtWidgets.QMessageBox.Ok)

        self.annotations_dir = ""
        while len(self.annotations_dir) == 0:
            self.annotations_dir = str(
                QFileDialog.getExistingDirectory(
                    self, "Select Annotations Directory", options=options))
            print(self.annotations_dir)
            self.annotation_paths = [
                f for f in glob.glob(self.annotations_dir + "**/*.json",
                                     recursive=False)
            ]
            if len(self.annotations_dir) == 0:
                QtWidgets.QMessageBox.question(
                    self, 'No directory selected.',
                    "Please select a directory for annotations",
                    QtWidgets.QMessageBox.Ok)

        self.num_videos = len(self.video_paths)
        self.current_video = 0

        self.annotations = {}

        for annotation_path in self.annotation_paths:
            j = json.load(open(annotation_path, "r"))
            self.annotations[j["name"]] = j

        print(self.annotation_paths)

        self.createVideoPlayer()

        self.createUI()

        self.createToolbar()

        self.statusbar = QStatusBar(self)

        self.setStatusBar(self.statusbar)

        self.current_annotation = "A"

        self.statusbar.showMessage("Current Annotation: " +
                                   self.current_annotation)

        self.createShortcuts()

        is_video_set = False
        for i, video_path in enumerate(self.video_paths):

            if "\\" in video_path:
                video_name = video_path.split("\\")[-1]
            else:
                video_name = video_path.split("/")[-1]

            if video_name not in self.annotations:
                self.file = self.OpenFile(video_path)

                self.current_video_attrs = self.annotations.get(
                    video_name, {
                        "name": video_name,
                        "path": video_path,
                        "annotations": {}
                    })
                self.annotations[self.current_video_attrs[
                    "name"]] = self.current_video_attrs
                self.current_video = i

                is_video_set = True

                break

        if not is_video_set:
            video_path = self.video_paths[0]
            if "\\" in video_path:
                video_name = video_path.split("\\")[-1]
            else:
                video_name = video_path.split("/")[-1]
            self.file = self.OpenFile(video_path)
            self.current_video_attrs = self.annotations.get(
                video_name, {
                    "name": video_name,
                    "path": video_path,
                    "annotations": {}
                })

            self.annotations[
                self.current_video_attrs["name"]] = self.current_video_attrs

        self.play()

        self.next_visible = True
        self.prev_visible = True
        self.setVisibilities()
Ejemplo n.º 49
0
 def directoryDialog(self):
     selected = QFileDialog.getExistingDirectory(
         self, 'Save images to the directory', self.directory.text(),
         QFileDialog.ShowDirsOnly)
     if selected:
         self.directory.setText(selected)
Ejemplo n.º 50
0
 def button_rawImgFold_clicked(self):
     self.rawImgFold = QFileDialog.getExistingDirectory(self, "Select the raw images folder")
     self.rawImgFold = Path(self.rawImgFold)
Ejemplo n.º 51
0
 def choiceDir(self):
     Dir_path = QFileDialog.getExistingDirectory(self, '请选择保存源代码路径', './')
     if Dir_path:
         self.lineEdit_codesave_path.setText(Dir_path)
     self.saveDir = self.lineEdit_codesave_path.text()
 def openDirectoryDialog(self):
     directory_chosen = str(
         QFileDialog.getExistingDirectory(self, "Select Directory"))
     self.output_box.setText(directory_chosen)
Ejemplo n.º 53
0
 def folderBrowserClicked(self):
     url = str(QFileDialog.getExistingDirectory(self, "Select Directory"))
     if url != "":
         self.__folderUrl = url + '/'
         self.ui.selectFolder_edit.setText(self.__folderUrl)
     print(self.__folderUrl)
Ejemplo n.º 54
0
 def download(self):
     self.setToNoColor()
     path = ""
     url = self.getUrl()
     fileName = self.getNameOfFile()
     # url and fileName is blank or url is non-existent show error and red mark the blank input field
     if url == "-1" and fileName == "-1":
         self.setErrorVisible(100, "red")
         self.error.setText("Invalid input in url.\n")
         self.error.setAlignment(QtCore.Qt.AlignCenter)
         self.error.append("Invalid input in file name.")
         self.error.setAlignment(QtCore.Qt.AlignCenter)
         self.fileName.setStyleSheet("background-color: red;")
         self.url.setStyleSheet("background-color: red;")
     # only url is blank or non-existent show error and red mark the url input field
     elif url == "-1":
         self.setErrorVisible(50, "red")
         self.error.setText("Invalid input in url.")
         self.error.setAlignment(QtCore.Qt.AlignCenter)
         self.url.setStyleSheet("background-color: red;")
     # only fileName is blank show error and red mark the url input field
     elif fileName == "-1":
         self.setErrorVisible(50, "red")
         self.error.setText("Invalid input in file name.")
         self.error.setAlignment(QtCore.Qt.AlignCenter)
         self.fileName.setStyleSheet("background-color: red;")
     # both inputs are includes valid
     else:
         self.error.setVisible(False)
         path = ""
         # getting last path when app was used if first usage or path not existing redirect to desktop when not
         # file not exist function create nwe
         checkIfFileExist("resources\\LastPath.txt")
         try:
             f = open("resources\\LastPath.txt", "r")
             lastPath = f.readline()
             f.close()
         # when file not created by function program exits with -3
         except FileNotFoundError:
             print(
                 "Cannot open file check if place where you installed file for file LastPath.txt in "
                 "resources directory if missing create new one")
             exit(-3)
         # checking whats in lastFile.txt and if exist
         if lastPath != "" and os.path.isdir(lastPath):
             path = QFileDialog.getExistingDirectory(
                 self, "select directory", lastPath,
                 QFileDialog.ShowDirsOnly)
         else:
             path = QFileDialog.getExistingDirectory(
                 self, "select directory",
                 expanduser("~") + "\Desktop", QFileDialog.ShowDirsOnly)
         # when close save dialog return none and when path not exist show error message
         if not os.path.isdir(path):
             if path == "":
                 return None
             else:
                 self.errorHandling(self, -2)
         #  if user choose mp3 download as mp3 and the same for mp4 with different message after downloaded
         if self.fileType.currentText() == "MP3":
             file = App.Download(url, self.fileType.currentText(), path,
                                 fileName)
             self.fileWillBeDownload(fileName)
             QApplication.processEvents()
             errorCode = file.downloadAsMp3()
             if errorCode == -4 or errorCode == -5 or errorCode == -6:
                 self.errorHandling(errorCode)
             else:
                 self.fileDownloaded(fileName, path, "MP3")
         elif self.fileType.currentText() == "MP4":
             file = App.Download(url, self.fileType.currentText(), path,
                                 fileName)
             self.error.setAlignment(QtCore.Qt.AlignCenter)
             self.fileWillBeDownload(fileName)
             QApplication.processEvents()
             if file.downloadAsMp4() != -4:
                 self.fileDownloaded(fileName, path, "MP4")
             else:
                 self.errorHandling(-4)
         else:
             print("error")
         # saving path for next usage when downloaded(lastPath for usage)
         checkIfFileExist("resources\\LastPath.txt")
         try:
             f = open("resources\\LastPath.txt", "w")
             f.write(path)
             f.close()
         except Exception as e:
             print("something goes wrong".format(e))
             exit(-3)
Ejemplo n.º 55
0
 def on_push_file_button(self):
     filename = QFileDialog.getExistingDirectory(self, '选择需要统计的目录', '')
     self.m_PathLineEdit.setText(filename)
Ejemplo n.º 56
0
 def select_data_folder(self):
     f_dialog = QFileDialog()
     f_dialog.setFileMode(QFileDialog.Directory)
     res = f_dialog.getExistingDirectory(self)
     if res:
         self.ui.data_folder_path.setText(res)
Ejemplo n.º 57
0
    def chooseDatasetFolder(self):

        folderName = QFileDialog.getExistingDirectory(self, "Choose a Folder to Export the Dataset", "")
        if folderName:
            self.editDatasetFolder.setText(folderName)
Ejemplo n.º 58
0
 def add_wps_binary_layer(self) -> None:
     folder = QFileDialog.getExistingDirectory(caption='Select WPS Binary Dataset Folder')
     if not folder:
         return
     load_wps_binary_layer(folder)
Ejemplo n.º 59
0
 def on_btn_choose_gnuradio_directory_clicked(self):
     directory = QFileDialog.getExistingDirectory(
         self, "Choose GNU Radio directory")
     if directory:
         self.ui.lineEditGnuradioDirectory.setText(directory)
         self.set_gnuradio_status()
Ejemplo n.º 60
0
 def chooseDir(self):
     directory = QFileDialog.getExistingDirectory(self, "选择工作路径", "./")
     self.lineEdit_4.setText(directory)