Python PyQt4.QtGui 模块,QFileDialog() 实例源码

我们从Python开源项目中,提取了以下32个代码示例,用于说明如何使用PyQt4.QtGui.QFileDialog()

项目:Comictagger    作者:dickloraine    | 项目源码 | 文件源码
def selectFile( self, control, name ):

        dialog = QtGui.QFileDialog(self)
        dialog.setFileMode(QtGui.QFileDialog.ExistingFile)

        if platform.system() == "Windows":
            if name == "RAR":
                filter  = self.tr("Rar Program (Rar.exe)")                      
            else:
                filter  = self.tr("Programs (*.exe)")   
            dialog.setNameFilter(filter)        
        else:
            dialog.setFilter(QtCore.QDir.Files) #QtCore.QDir.Executable | QtCore.QDir.Files)
            pass

        dialog.setDirectory(os.path.dirname(str(control.text())))
        dialog.setWindowTitle("Find " + name + " program")

        if (dialog.exec_()):
            fileList = dialog.selectedFiles()
            control.setText( str(fileList[0]) )
项目:SHIP    作者:duncan-r    | 项目源码 | 文件源码
def saveFileDialog(self, path='', file_types='ALL (*.*)'):
        """Launches an save-file dialog

        file_types should be a formatted string setup as follows:
        "CSV (*.csv);;TXT (*.txt)"

        Args:
            path (str): the preset path to launch the dialog in.
            file_types (str): the extensions to filter the files with  

        Returns:
            str - containing the chosen file path or False if cancelled.
        """
        filename = str(QtGui.QFileDialog.getSaveFileName(self, 'Save File', path, file_types))
        if not filename == '':
            logger.info('Saving file: Filename = ' + filename)
            return filename
        else:
            logger.info('User cancelled file save process')
            return False
项目:SHIP    作者:duncan-r    | 项目源码 | 文件源码
def dirFileDialog(self, path=''):
        """Launches a dialog to choose directories from.

        Args:
            path (str): Optional - the preset path to launch the dialog in.

        Returns:
            str - containing the chosen file path or False if cancelled.
        """
        file_path = str(QtGui.QFileDialog.getExistingDirectory(self, 
                    caption='Select Directory', directory=path,
                    options=QtGui.QFileDialog.ShowDirsOnly))

        if not file_path == '':
            logger.info('Selected directory: Filepath = ' + file_path)
            return file_path
        else:
            logger.info('User cancelled get directory process')
            return False
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def getOpenFileNameAndEncoding(self, title, dir, filter):
        dialog = QtGui.QFileDialog()
        dialog.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)
        dialog.setFilter(filter)
        dialog.setWindowTitle(title)

        encodings = Conf.value('import-post-decode')
        keys = sorted(encodings.keys())
        combo = QtGui.QComboBox()
        combo.addItems(["%s (%s)" % (k, encodings[k]) for k in keys])
        combo.setCurrentIndex(
            keys.index(
                Conf.value('import-post-decode-default')))

        grid = dialog.layout()
        grid.addWidget(QtGui.QLabel(Lang.value('MISC_Encoding')), 4, 0)
        grid.addWidget(combo, 4, 1)

        fileName = False
        if dialog.exec_() and len(dialog.selectedFiles()):
            fileName = dialog.selectedFiles()[0]
        return fileName, keys[combo.currentIndex()]
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def onExportPdf(self):
        default_dir = './collections/'
        fileName = QtGui.QFileDialog.getSaveFileName(
            self,
            Lang.value('MI_Export') +
            ' ' +
            Lang.value('MI_Export_PDF'),
            default_dir,
            "(*.pdf)")
        if not fileName:
            return
        try:
            ed = pdf.ExportDocument(Mainframe.model.entries, Lang)
            ed.doExport(unicode(fileName))
        except IOError:
            msgBox(Lang.value('MSG_IO_failed'))
        except:
            msgBox(Lang.value('MSG_PDF_export_failed'))
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def onSaveSelectionAs(self):
        default_dir = './collections/'
        if Mainframe.model.filename != '':
            default_dir, tail = os.path.split(Mainframe.model.filename)
        fileName = QtGui.QFileDialog.getSaveFileName(
            self, Lang.value('MI_Save_selection_as'), default_dir, "(*.olv)")
        if not fileName:
            return

        f = open(unicode(fileName), 'w')
        try:
            f.write(self.getSelectionAsYaml().encode('utf8'))
        except IOError:
            msgBox(Lang.value('MSG_IO_failed'))
        finally:
            f.close()
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, main, *args, **kwargs):
        QtGui.QFileDialog.__init__(self, *args, **kwargs)
        self.setDirectory(QtCore.QDir.homePath())
#        self.setDirectory('/home/mauriziob/data/code/blofeld/test/')
        self.main = main
        self.setOption(self.DontUseNativeDialog)
        self.setAcceptMode(self.AcceptOpen)
        self.setFileMode(self.ExistingFile)
        self.buttonBox = self.findChildren(QtGui.QDialogButtonBox)[0]
        self.open_btn = [b for b in self.buttonBox.buttons() if self.buttonBox.buttonRole(b) == QtGui.QDialogButtonBox.AcceptRole][0]
        self.setNameFilters(('Wave files (*.wav)', 'Any files (*)'))
        self.setSidebarUrls([QtCore.QUrl.fromLocalFile(QtCore.QDir.homePath()), QtCore.QUrl.fromLocalFile(QtGui.QDesktopServices.storageLocation(QtGui.QDesktopServices.MusicLocation))])

        self.splitter = self.findChildren(QtGui.QSplitter)[0]
        self.wave_panel = WavePanel(self)
        self.wave_panel.isValid.connect(self.open_enable)
        self.valid = False

        self.splitter.addWidget(self.wave_panel)
        self.splitter.setCollapsible(2, False)
        self.currentChanged.connect(self.wave_panel.setWave)
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(H5SaveDialog, self).__init__(*args, **kwargs)

        self.setAcceptMode(QtGui.QFileDialog.AcceptSave)
        self.setFileMode(QtGui.QFileDialog.AnyFile)

        self.chk_branches.setChecked(True)
        self.chk_freehand.setChecked(True)
        self.chk_pixel.setChecked(True)
        self.chk_circles.setChecked(True)
        self.chk_traces.setChecked(True)
        self.chk_data.setChecked(False)
        self.chk_mask.setChecked(True)
        self.chk_segmentation.setChecked(True)

        self.chk_branches.setToolTip("Store the branch rois in the hdf5 file.")
        self.chk_freehand.setToolTip("Store the freehand rois in the hdf5 file.")
        self.chk_pixel.setToolTip("Store the pixel rois in the hdf5 file.")
        self.chk_circles.setToolTip("Store the circle rois in the hdf5 file.")
        self.chk_traces.setToolTip("Also store the traces of all selected rois as shown in the current preview.")
        self.chk_data.setToolTip("Store the 3D video data the hdf5 file.\n " + \
                                 "This will significantly increase the filesize.")
        self.chk_mask.setToolTip("Store the threshold value and binary mask in the hdf5 file.")
        self.chk_segmentation.setToolTip("Store your segmentations")
项目:barium    作者:barium-project    | 项目源码 | 文件源码
def save(self):
        dialog = QtGui.QFileDialog()
        dialog.setDirectory('C:\Users\barium133\Code\barium\lib\clients\MassSpecExperiment_client')
        filepath = str(dialog.getSaveFileName())
        print filepath
        number_of_dataruns = self.experiment_tree.topLevelItemCount()
        array=[]
        for i in range(number_of_dataruns):
            datarun = self.experiment_tree.topLevelItem(i)
            number_of_scans = datarun.childCount()
            print datarun.text(0)
            line = []
            line.append(str(datarun.text(0)))
            for j in range(number_of_scans):
                scan = datarun.child(j)
                print scan.text(0)
                line.append(str(scan.text(0)))
            array.append(line)
        np.savetxt(filepath,array,fmt='%s')
        yield None
项目:MidiMemo    作者:MaurizioB    | 项目源码 | 文件源码
def autosave_path(self):
        def check():
            path = win.selectedFiles()[0]
            if QtCore.QFileInfo(path).permissions() & QtCore.QFile.WriteOwner:
                win.accept()
                self.autosave_path_edit.setText(path)
            else:
                QtGui.QMessageBox.warning(win, 'Write error', 'The selected path has no write permissions.')
        win = QtGui.QFileDialog(self, 'Select output directory')
        win.setFileMode(QtGui.QFileDialog.Directory)
        win.setOptions(QtGui.QFileDialog.ShowDirsOnly|QtGui.QFileDialog.HideNameFilterDetails)
        win.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
        buttonBox = win.findChild(QtGui.QDialogButtonBox)
        open_btn = buttonBox.button(QtGui.QDialogButtonBox.Open)
        open_btn.clicked.disconnect()
        open_btn.clicked.connect(check)
        return win.exec_()
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def exportDatabase(self):
        fileNameAndPath = QtGui.QFileDialog().getSaveFileName(self, "Export database to file", "", '*.sqlite')

        try:
            filePath = '/'.join(str(fileNameAndPath).split('/')[:-1])
        except UnicodeEncodeError:
            QtGui.QMessageBox.critical(self, 'Error', "Export failed.\nPlease select a filename and path with latin characters.", QtGui.QMessageBox.Close)
            return

        if fileNameAndPath != "":

            # Copy database to directory
            copyfile('database/myDB.sqlite', fileNameAndPath)

            QtGui.QMessageBox.information(self, 'Success', "Current database was successfully saved in\n " + filePath + ".", QtGui.QMessageBox.Close)

        #Log
        Functions.addEntryToLog("Current database was exported in " + filePath)
        # Reload all tables in preferences
        self.loadAllTablesInPreferences()
项目:Comictagger    作者:dickloraine    | 项目源码 | 文件源码
def selectFile( self , folder_mode = False):

        dialog = QtGui.QFileDialog(self)
        if folder_mode:
            dialog.setFileMode(QtGui.QFileDialog.Directory)
        else:
            dialog.setFileMode(QtGui.QFileDialog.ExistingFiles)

        if self.settings.last_opened_folder is not None:
            dialog.setDirectory( self.settings.last_opened_folder )
        #dialog.setFileMode(QtGui.QFileDialog.Directory )

        if not folder_mode:
            if platform.system() != "Windows" and utils.which("unrar") is None:
                archive_filter = "Comic archive files (*.cbz *.zip)"
            else:
                archive_filter = "Comic archive files (*.cbz *.zip *.cbr *.rar)"
            filters  = [ 
                         archive_filter,
                         "Any files (*)"
                         ]
            dialog.setNameFilters(filters)

        if (dialog.exec_()):
            fileList = dialog.selectedFiles()
            #if self.dirtyFlagVerification( "Open Archive",
            #                           "If you open a new archive now, data in the form will be lost.  Are you sure?"):
            self.fileSelectionList.addPathList( fileList )
项目:PySCUBA    作者:GGiecold    | 项目源码 | 文件源码
def selectDataset(self):
        dataFileDialog = QtGui.QFileDialog(self)
        self.data_path = str(dataFileDialog.getOpenFileName())
        self.statusbar.showMessage("{0} ready to be "
            "analyzed".format(path.basename(self.data_path)))
        self.cancelButton.setEnabled(True)
        self.okButton.setEnabled(True)
项目:PySCUBA    作者:GGiecold    | 项目源码 | 文件源码
def selectDisplay(self):
        filters = 'Images (*.jpg *.pdf *.png)'
        select_filters = 'Images (*.jpg *.pdf *.png)'
        source_file = QtGui.QFileDialog.getOpenFileName(self, 
            'Select file to display', self.directory, filters, select_filters)

        self.load_image_thread = LoadImageThread(source_file)
        self.connect(self.load_image_thread, QtCore.SIGNAL("showImage(QString)"),
            self.showImage)
        self.load_image_thread.start()
项目:SHIP    作者:duncan-r    | 项目源码 | 文件源码
def openFileDialog(self, path='', file_types='ALL (*.*)', multi_file=False):
        """ Launches an open-file dialog.

        file_types should be a formatted string setup as follows:
        "CSV (*.csv);;TXT (*.txt)"

        Args:
            path (str): the preset path to launch the dialog in.
            file_types (str): the extensions to filter the files with. 

        Returns:
            str - containing the chosen file path or False if cancelled.
        """
        if not HAS_QT:
            return False

        if not multi_file:
            filename = str(QtGui.QFileDialog.getOpenFileName(self, 'Open File', path, file_types))
            if not filename == '':
                logger.info('Opening file: ' + filename)
                return filename
            else:
                logger.info('User cancelled file open process')
                return False
        else:
            filenames = QtGui.QFileDialog.getOpenFileNames(self, 'Open Files', path, file_types)
            if not len(filenames) < 1:
                str_names = []
                for f in filenames:
                    str_names.append(str(f))
                logger.info('Opening files: %s' % str(str_names))
                return str_names
            else:
                logger.info('User cancelled file open process')
                return False
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def onOpenFile(self):
        if not self.doDirtyCheck():
            return
        default_dir = './collections/'
        if Mainframe.model.filename != '':
            default_dir, tail = os.path.split(Mainframe.model.filename)
        fileName = QtGui.QFileDialog.getOpenFileName(
            self, Lang.value('MI_Open'), default_dir, "(*.olv)")
        if not fileName:
            return
        self.openCollection(fileName)
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def onSaveFileAs(self):
        default_dir = './collections/'
        if Mainframe.model.filename != '':
            default_dir, tail = os.path.split(Mainframe.model.filename)
        fileName = QtGui.QFileDialog.getSaveFileName(
            self, Lang.value('MI_Save_as'), default_dir, "(*.olv)")
        if not fileName:
            return
        Mainframe.model.filename = unicode(fileName)
        self.onSaveFile()
项目:olive-gui    作者:dturevski    | 项目源码 | 文件源码
def onImportPbm(self):
        if not self.doDirtyCheck():
            return
        default_dir = './collections/'
        if Mainframe.model.filename != '':
            default_dir, tail = os.path.split(Mainframe.model.filename)
        #fileName = QtGui.QFileDialog.getOpenFileName(self, Lang.value('MI_Import_PBM'), default_dir, "(*.pbm)")
        fileName, encoding = self.getOpenFileNameAndEncoding(
            Lang.value('MI_Import_PBM'), default_dir, "(*.pbm)")
        if not fileName:
            return
        try:
            Mainframe.model = model.Model()
            Mainframe.model.delete(0)
            file = open(unicode(fileName))
            pbm.PBM_ENCODING = encoding
            for data in pbm.PbmEntries(file):
                Mainframe.model.add(model.makeSafe(data), False)
            file.close()
            Mainframe.model.is_dirty = False
        except IOError:
            msgBox(Lang.value('MSG_IO_failed'))
        except:
            msgBox(Lang.value('MSG_PBM_import_failed'))
        finally:
            if len(Mainframe.model.entries) == 0:
                Mainframe.model = model.Model()
            self.overview.rebuild()
            Mainframe.sigWrapper.sigModelChanged.emit()
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def accept(self):
        if self.valid:
            QtGui.QFileDialog.accept(self)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def exec_(self):
        res = QtGui.QFileDialog.exec_(self)
        if res:
            return self.selectedFiles()[0]
        return res
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def __init__(self, mode=ALLFILE, *args, **kwargs):
        QtGui.QFileDialog.__init__(self, *args, **kwargs)
        if mode == ALLFILE:
            self.setNameFilters([_file_types[ALLFILE], _file_types[MIDFILE], _file_types[SYXFILE], 'Any files (*)'])
        else:
            self.setNameFilters([_file_types[mode], 'Any files (*)'])
        self.mode = mode
        self.res = None
        self.setWindowTitle(_titles[mode])
        self.setFileMode(QtGui.QFileDialog.ExistingFile)
        self.setOption(QtGui.QFileDialog.HideNameFilterDetails, True)
        self.setAcceptMode(QtGui.QFileDialog.AcceptOpen)
        self.setFileMode(QtGui.QFileDialog.ExistingFile)
        self.setDirectory(QtCore.QDir.homePath())
        urls = []
        if mode == MIDFILE|SYXFILE:
            urls.append(_factory)
        if mode & MIDFILE:
            urls.append(_midi_sets)
        if mode & SYXFILE:
            urls.append(_single_sets)
        self.setSidebarUrls(urls)
        buttonBox = self.findChildren(QtGui.QDialogButtonBox)[0]
        buttonBox.removeButton(buttonBox.button(QtGui.QDialogButtonBox.Open))
        self.import_btn = QtGui.QPushButton('Import')
        self.import_btn.clicked.connect(self.accept)
        self.import_btn.setIcon(self.style().standardIcon(QtGui.QStyle.SP_DialogOpenButton))
        buttonBox.addButton(self.import_btn, QtGui.QDialogButtonBox.ActionRole)

        self.currentChanged.connect(lambda path: self.import_btn.setText('Open' if QtCore.QFileInfo(path).isDir() else 'Import'))
项目:SamuROI    作者:samuroi    | 项目源码 | 文件源码
def __init__(self, *args, **kwargs):
        super(H5LoadDialog, self).__init__(*args, **kwargs)

        self.setFileMode(QtGui.QFileDialog.ExistingFile)
        self.setAcceptMode(QtGui.QFileDialog.AcceptOpen)

        self.chk_branches.setEnabled(False)
        self.chk_freehand.setEnabled(False)
        self.chk_pixel.setEnabled(False)
        self.chk_circles.setEnabled(False)
        self.chk_traces.setEnabled(False)
        self.chk_data.setEnabled(False)
        self.chk_mask.setEnabled(False)
        self.chk_segmentation.setEnabled(False)

        self.chk_branches.setToolTip("Load the branch rois from the hdf5 file.")
        self.chk_freehand.setToolTip("Load the freehand rois from the hdf5 file.")
        self.chk_pixel.setToolTip("Load the pixel rois from the hdf5 file.")
        self.chk_circles.setToolTip("Load the circle rois from the hdf5 file.")
        self.chk_traces.setToolTip("The traces can never be loaded from hdf files,\n" + \
                                   " since they are defined by the masks and the data.")
        self.chk_data.setToolTip("Load the 3D video data from the hdf5 file.\n " + \
                                 "This will discard the currently selected dataset.")
        self.chk_mask.setToolTip("Load the threshold value and binary mask from the hdf5 file.")
        self.chk_segmentation.setToolTip("Load your segmentations")

        self.currentChanged.connect(self.update_checkboxes)
项目:barium    作者:barium-project    | 项目源码 | 文件源码
def load(self):
        dialog = QtGui.QFileDialog()
        dialog.setDirectory('C:\Users\barium133\Code\barium\lib\clients\MassSpecExperiment_client')
        filepath = str(dialog.getOpenFileName())
        settings = np.loadtxt(filepath,dtype=str,delimiter='\n')
        print settings
        yield None
项目:ChiantiPy    作者:chianti-atomic    | 项目源码 | 文件源码
def chpicker(dir, filter='*.*', label='ChiantiPy'):
    '''Select a filename using a Qt gui dialog.'''
    app=QtGui.QApplication(sys.argv)
    a=QtGui.QFileDialog()
    a.setDirectory(dir)
    a.setFilter(filter)
#    mylabel=QtCore.QString('some label')
#    a.setLabelText(mylabel)
    a.setWindowTitle(label)
    a.setModal(True)
    a.exec_()
    qfilename=a.selectedFiles()
    return str(qfilename[0])
    #
#
项目:ImageSegLoaderPart    作者:Layman806    | 项目源码 | 文件源码
def selectWindow(self):
        '''
            This function will first open a file dialog box.
            There we will select an Image file.
            And then a preview is created for that image,
            while the image is given as input to scanFunction().
        '''
        fileDialog = QtGui.QFileDialog()
        self.pic = fileDialog.getOpenFileName()
        pixmap = QtGui.QPixmap(self.pic)
        w = pixmap.width()
        h = pixmap.height()
        center = int((641 - w) / 2)
        # print(center)

        if center < 0:
            pixmap = pixmap.scaledToHeight(201)
            w = pixmap.width()
            h = pixmap.height()
            center = int((641 - w) / 2)
            self.labelForPicture.setGeometry(center, 0, w, 201)
        elif center >= 0:
            self.labelForPicture.setGeometry(center, 0, w, 201)

        if w > h:
            if h < 201:
                pixmap = pixmap.scaledToWidth(w)
            elif h > 201:
                pixmap = pixmap.scaledToHeight(201)
                w = pixmap.width()
                h = pixmap.height()
                center = int((641 - w) / 2)
                self.labelForPicture.setGeometry(center, 0, w, h)

        elif w == h and h <= 201:
            pixmap = pixmap.scaledToHeight(h)
        elif w < h:
            pixmap = pixmap.scaledToHeight(201)
        self.labelForPicture.setPixmap(pixmap)
        self.labelForPicture.show()
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def importDatabase(self):
        # Select database file to import
        fileNameAndPath = QtGui.QFileDialog().getOpenFileName(self, "Select a database to import", "", '*.sqlite')

        if fileNameAndPath != "":

            try:
                test = str(fileNameAndPath)
            except UnicodeEncodeError:
                QtGui.QMessageBox.critical(self, 'Error', "Import failed.\nPlease select a filename and path with latin characters.", QtGui.QMessageBox.Close)
                return

            # Check if database is valid (with queries)
            if Functions.checkIfProphetDatabase(str(fileNameAndPath)) == False:
                QtGui.QMessageBox.critical(self, 'Error', "Not a PROPheT database file.\nOperation cancelled.", QtGui.QMessageBox.Close)
                return

            # Copy new database
            copyfile(fileNameAndPath, 'database/myDB.sqlite')
            QtGui.QMessageBox.information(self, 'Success', "Selected database was successfully imported.", QtGui.QMessageBox.Close)

            # Set selected endpoint DBpedia
            Functions.setSettingToDB('endpoint_url', 'http://dbpedia.org/sparql')

            #Log
            Functions.addEntryToLog("Selected database was imported in PROPheT")

            # Reload all tables in preferences
            self.loadAllTablesInPreferences()
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def btnOpenFile_clicked(self):
        fileName = QtGui.QFileDialog.getOpenFileName(self, 'Select a file to open', "", '*.owl;;*.rdf;;*.ttl;;All files (*.*)')
        if fileName:
            self.ui.lineEditModelURL.setText(fileName)
项目:Bigglesworth    作者:MaurizioB    | 项目源码 | 文件源码
def accept(self):
        if not self.selectedFiles(): return
        path = self.selectedFiles()[0]
        stats = QtCore.QFileInfo(path)
        if stats.isDir():
            self.setDirectory(path)
            return
        if not stats.exists():
            return
        if self.mode & MIDFILE:
            sound_list = []
            try:
                pattern = midifile.read_midifile(str(path.toUtf8()))
                for track in pattern:
                    for event in track:
                        if isinstance(event, midifile.SysexEvent) and len(event.data) == 392:
                            sound_list.append(Sound(event.data[6:391]))
                if sound_list:
                    self.res = sound_list, path
                    return QtGui.QFileDialog.accept(self)
                elif self.mode == MIDFILE:
                    nomidi_msgbox(self)
                    return
            except:
                if self.mode == MIDFILE:
                    nomidi_msgbox(self)
                    return
        if self.mode & SYXFILE:
            try:
                with open(str(path.toUtf8()), 'rb') as sf:
                    sysex = list(ord(i) for i in sf.read())
                if len(sysex) == 392:
                    self.res = Sound(sysex[5:-2]), path
                    return QtGui.QFileDialog.accept(self)
                elif len(sysex) == 26240 and (sysex[1:3] == [IDW, IDE] and sysex[4] == WTBD and sysex[7] == 0):
                    self.res = Wavetable(sysex), 
                    return QtGui.QFileDialog.accept(self)
                elif self.mode == SYXFILE:
                    nosysex_msgbox(self)
                    return
            except:
                if self.mode == SYXFILE:
                    nosysex_msgbox(self)
                    return
        none_msgbox(self)
        return
项目:MidiMemo    作者:MaurizioB    | 项目源码 | 文件源码
def export(self):
        res = QtGui.QFileDialog.getSaveFileName(
                                                self, 
                                                'Export to MIDI file', 
                                                self.file_name, 
                                                ('MIDI file (*.mid)(*.mid);;Show all files (*)'), 
                                                )
        if not res:
            return

        self.file_name = str(res)

        tick_res = defaults['tick_res']
        pattern = midi.Pattern(resolution=tick_res)
        track_dict = {}
        for line in range(self.dest_model.rowCount()):
            if not self.dest_model.item(line).data(EnabledRole).toBool(): continue
            item = self.dest_model.item(line)
            track = midi.Track(tick_relative=False)
            pattern.append(track)
            track_dict[item.data(DestRole).toPyObject()] = track
            track.append(midi.TrackNameEvent(data=[b for b in bytearray(str(item.text()))]))
#        pattern[0].append(midi.SetTempoEvent(bpm=self.dest_bpm_spin.value()))
        source_bpm = self.src_bpm_spin.value()

        for event, time, source, enabled in self.event_buffer:
            if isinstance(event, ConnectionEvent): continue
            if not enabled and not self.disabled_chk.isChecked: continue
            _, _, dest = source
            if dest not in track_dict.keys(): continue
            #event check for "fake" NOTEON with velocity=0, which are considered as NOTEOFF
            event_type = event.type
            if event_type == NOTEON and event.data2 == 0:
                event_type = NOTEOFF
            if event_type in self.filter['event_type']: continue

            event_class, dest_attr = ev_dict[event.type]
            if isinstance(dest_attr, list):
                data = [getattr(event, attr) for attr in dest_attr]
            else:
                data = dest_attr(event)
                print 'sysex! sysex={}, data={}'.format(event.sysex, data)
            ticks = int((time*10**-9)/60.*source_bpm*tick_res)
            output_event = event_class(tick=ticks, channel=event.channel, data=data)
            track_dict[dest].append(output_event)
        for track in pattern:
            last_tick = track[-1].tick
            track.append(midi.EndOfTrackEvent(tick=last_tick))

        pattern.make_ticks_rel()
        print pattern
        for event, time, source, enabled in self.event_buffer:
            if event.type == SYSEX:
                print event.sysex
        midi.write_midifile(self.file_name, pattern)
        if self.close_chk.isChecked():
            self.accept()
项目:PH5    作者:PIC-IRIS    | 项目源码 | 文件源码
def save2file(self, saveType):
        w = self.width
        h = self.height
        if w == 0:
            w = 700
            h = 500
        # call dialog to change the size of the image
        vals = PrintSaveParaDialog.print_save(self, saveType, 'pixels', (w, h) )
        if vals==None: return 
        w, h, legend, saveType, fileformat = vals[0], vals[1],vals[2], vals[3], vals[4]

        # QFileDialog to set the name of the new image file                
        dialog = QtGui.QFileDialog(self.parent)
        dialog.setFileMode(QtGui.QFileDialog.AnyFile)
        fname = dialog.getSaveFileName(self.parent, 'Save As', '', '*.%s' % fileformat)
        if fname =='': return

        if "." + fileformat not in fname:
            fname = fname + "." + fileformat
        print "Image will be saved to:", fname

        showStatus("Preparing","")
        start = time.time()
        staNo = self.control.PH5Info['numOfStations'] 
        # clear the old figure
        plt.clf()
        fig = plt.figure(1, dpi=100)
        #if fileformat=='svg':
        #    fig.set_size_inches(w/10, h/10, forward=True)
        #else:
        fig.set_size_inches(w/100, h/100, forward=True)
        # set tight layout to save space for image
        fig.set_tight_layout(True)
        # plot data
        self.painting(saveType, legend)

        # remove the old five before saving the new one
        try:
            os.remove(fname)
        except: pass
        # save figure with dpi=100. The dpi and w, h has been tried to get the right size for the file
        if fileformat=='svg':
            plt.savefig(str(fname))
        else:
            plt.savefig(str(fname), dpi=1000)

        end = time.time()

        showStatus("","Done Saving in %s seconds" % (end-start))       

    ###################################
    # Author: Lan
    # def: painting():201509
    # plot data using matplotlib package
    # all data just need to be the same scale (using the sentXXX), 
    #   1. plot data    2. plot gridlines   3. plot H/V labels + title   4. plot axis labels 
    #   to paint the zoomview: 
    #    + limit stations
    #    + draw the whole data of the station in that window (data after trimming)
    #    + use ax.set_ylim to limit
项目:PH5    作者:PIC-IRIS    | 项目源码 | 文件源码
def onFile(self):
        dialog = QtGui.QFileDialog(self)
        dialog.setFileMode(QtGui.QFileDialog.ExistingFile)
        fname = dialog.getOpenFileName(self, 'Open', '/home/field/Desktop/data', 'master.ph5') 
        print fname

        if fname == "": 
            errorMsg = "Can't find the ph5 file: %s" % fname
            QtGui.QMessageBox.question(self, 'Error', errorMsg, QtGui.QMessageBox.Ok)
            return

        self.fname = fname
        self.eventGui.clearArrays()
        self.stationGui.clearArrays()
        try: del self.arrays
        except: pass
        try: del self.events
        except: pass
        gc.collect()

        PH5Object = ph5_viewer_reader.PH5Reader()
        PH5Object.initialize_ph5(self.fname)
        PH5Object.createGraphExperiment()
        PH5Object.createGraphEvents()
        PH5Object.createGraphArraysNStations()
        self.arrays = deepcopy(PH5Object.graphArrays)
        self.events = deepcopy(PH5Object.graphEvents)
        #self.eventGui.setChannels()
        #self.stationGui.setChannels()

        self.eventGui.setArrays()
        self.stationGui.setArrays()

        self.tabWidget.setCurrentIndex(1)    # view tab Events
        self.mainControl.setWidgetsEnabled(False)
        self.graphName = "%s %s" % (PH5Object.graphExperiment['experiment_id_s'], PH5Object.graphExperiment['nickname_s'])

        self.eventGui.setNotice(self.graphName)
        self.stationGui.setNotice(self.graphName)
        self.mainControl.mainPlot.setWindowTitle('Main Window -  %s' % (self.graphName))
        self.mainControl.supportPlot.setWindowTitle('Support Window -  %s' % (self.graphName))
        # close all opened files and remove PH5Object when done to save resources
        PH5Object.ph5close()
        del PH5Object
        gc.collect()
        #print "begin testing"
        #PH5Object = ph5_viewer_reader.PH5Reader()
        #PH5Object.initialize_ph5('/home/field/Desktop/data/10-016/master.ph5')
        #print "finish testing"

    ###################################
    # Author: Lan
    # def: onSaveMainWindow():201410
项目:prophet    作者:MKLab-ITI    | 项目源码 | 文件源码
def showFileDialogSaveGraph(self):

        # if there is no graph to save
        if (self.getGraph()).__len__() == 0:
            # Show message box with error
            QtGui.QMessageBox.critical(self, 'Error', "There is no model to export.", QtGui.QMessageBox.Close)

        else:
            fileDialog = QtGui.QFileDialog()
            fileNameAndPath = fileDialog.getSaveFileName(self, "Export Graph to file", "", '*.owl;;*.rdf;;*.ttl;;*.nt;;*.n3')

            try:
                str(fileNameAndPath)
            except UnicodeEncodeError:
                QtGui.QMessageBox.critical(self, 'Error', "Export Graph to file failed.\nPlease select a filename and path with latin characters.", QtGui.QMessageBox.Close)
                return

            # If user selected a file
            if fileNameAndPath != "":
                # Define a file inside our directory to export
                tempLocalFile = str('temp_export_file.' + fileNameAndPath.split('.')[-1])
                tempLocalFileAbsolutePath = path.abspath(tempLocalFile)

                # Serialize graph to temp file
                (window.getGraph()).serialize(tempLocalFileAbsolutePath, util.guess_format(tempLocalFileAbsolutePath))

                # Copy temp file to selected fileNameAndPath
                copyfile(tempLocalFile, str(fileNameAndPath))

                # Delete temp file
                remove(tempLocalFile)

                # Prepare strings for message
                fileName = str(fileNameAndPath).split("/")[-1]
                filePath = '/'.join(str(fileNameAndPath).split('/')[:-1])

                QtGui.QMessageBox.information(self, 'Success', "File " + fileName + "\n was successfully saved in\n " + filePath + ".", QtGui.QMessageBox.Close)

                # Log
                Functions.addEntryToLog("Model " + self.getMyModelName() + " was exported to " + fileNameAndPath)

                # Change changesMadeToModel boolean to false, since all changes are considered saved
                self.setChangesMadeToModel(False)