def setup(self, parent=None, caption=str("Sélectionnez")) : self.setFileMode(self.ExistingFiles) icon = QtGui.QIcon() icon.addPixmap(QtGui.QPixmap(_fromUtf8("resources/PL128.png")), QtGui.QIcon.Normal, QtGui.QIcon.Off) self.setWindowIcon(icon) mydir = str(os.environ['USERPROFILE']) thedir = QDir("C:/") self.setDirectory(thedir) url = [] url.append(QUrl.fromLocalFile(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation))) url.append(QUrl.fromLocalFile(QDesktopServices.storageLocation(QDesktopServices.DesktopLocation))) url.append(QUrl.fromLocalFile(QDesktopServices.storageLocation(QDesktopServices.HomeLocation))) url.append(QUrl('file:')) self.setSidebarUrls(url) # self.setDirectory(mydir) self.setWindowModality(QtCore.Qt.ApplicationModal) MyFileDialog.setNameFilter(self, "Epub (*.epub)") self.setLabelText(self.LookIn, "Regarder dans :") self.setLabelText(self.FileName, "Fichier") self.setLabelText(self.FileType, "Type de fichier") self.setLabelText(self.Accept, "Ouvrir") self.setLabelText(self.Reject, "Annuler") self.setWindowTitle("Sélectionnez un ou plusieurs fichiers") self.setOption(self.DontUseNativeDialog, False) # self.setOption(self.DontResolveSymlinks, True) self.setOption(self.ShowDirsOnly, False) self.tree = self.findChild(QtGui.QTreeView) self.init_ui() self.filesSelected.connect(self.cur_change) self.filesSelected.connect(self.choose_file)
def select_output_file(self): if self.dlg.rbSTLASCII.isChecked() or self.dlg.rbSTLbinary.isChecked(): filename = QFileDialog.getSaveFileName(self.dlg, "Select output file ", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation) , '*.stl') self.dlg.lineEdit.setText(filename) elif self.dlg.rbTXT.isChecked(): filename = QFileDialog.getSaveFileName(self.dlg, "Select output file ", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation) , '*.txt') self.dlg.lineEdit.setText(filename)
def getDataDir(): if isOSX(): return os.path.join(unicode(QDesktopServices.storageLocation(QDesktopServices.DataLocation)), "Pesterchum/") elif isLinux(): return os.path.join(unicode(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)), ".pesterchum/") else: return os.path.join(unicode(QDesktopServices.storageLocation(QDesktopServices.DataLocation)), "pesterchum/")
def __init__(self, args, parent = None): QObject.__init__(self, parent) # variable declarations self.m_loadStatus = self.m_state = QString() self.m_var = self.m_paperSize = self.m_loadScript_cache = {} self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_clipRect = QRect() # setup the values from args self.m_script = QString.fromUtf8(args.script.read()) self.m_scriptFile = args.script.name self.m_args = args.script_args self.m_upload_file = args.upload_file autoLoadImages = False if args.load_images == 'no' else True pluginsEnabled = True if args.load_plugins == 'yes' else False args.script.close() palette = self.m_page.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_page.setPalette(palette) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.settings().setAttribute(QWebSettings.AutoLoadImages, autoLoadImages) self.m_page.settings().setAttribute(QWebSettings.PluginsEnabled, pluginsEnabled) self.m_page.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_page.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_page.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_page.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_page.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_page.mainFrame().setHtml('<html><body></body></html>') self.m_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) # if our script was called in a different directory, change to it # to make any dealings with files be relative to the scripts directory if os.path.dirname(self.m_scriptFile): os.chdir(os.path.dirname(self.m_scriptFile)) if self.m_verbose: m_netAccessMan = NetworkAccessManager(args.disk_cache, self) self.m_page.setNetworkAccessManager(m_netAccessMan) # inject our properties and slots into javascript self.connect(self.m_page.mainFrame(), SIGNAL('javaScriptWindowObjectCleared()'), self.inject) self.connect(self.m_page, SIGNAL('loadFinished(bool)'), self.finish)
def __init__(self, args, parent=None): QObject.__init__(self, parent) # variable declarations self.m_loadStatus = self.m_state = '' self.m_var = self.m_paperSize = self.m_loadScript_cache = {} self.m_verbose = args.verbose self.m_page = WebPage(self) self.m_clipRect = QRect() # setup the values from args self.m_script = args.script.read() self.m_scriptFile = args.script.name self.m_scriptDir = os.path.dirname(args.script.name) + '/' self.m_args = args.script_args self.m_upload_file = args.upload_file autoLoadImages = False if args.load_images == 'no' else True pluginsEnabled = True if args.load_plugins == 'yes' else False args.script.close() do_action('PhantomInitPre', Bunch(locals())) palette = self.m_page.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_page.setPalette(palette) if not args.proxy: QNetworkProxyFactory.setUseSystemConfiguration(True) else: proxy = QNetworkProxy(QNetworkProxy.HttpProxy, args.proxy[0], int(args.proxy[1])) QNetworkProxy.setApplicationProxy(proxy) self.m_page.settings().setAttribute(QWebSettings.AutoLoadImages, autoLoadImages) self.m_page.settings().setAttribute(QWebSettings.PluginsEnabled, pluginsEnabled) self.m_page.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_page.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_page.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_page.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_page.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_page.mainFrame().setHtml('<html><body></body></html>') self.m_page.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_page.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) m_netAccessMan = NetworkAccessManager(args.disk_cache, args.ignore_ssl_errors, self) self.m_page.setNetworkAccessManager(m_netAccessMan) # inject our properties and slots into javascript self.m_page.mainFrame().javaScriptWindowObjectCleared.connect(self.inject) self.m_page.loadFinished.connect(self.finish) do_action('PhantomInitPost', Bunch(locals()))
def getDataDir(): # Temporary fix for non-ascii usernames # If username has non-ascii characters, just store userdata # in the Pesterchum install directory (like before) try: if isOSX(): return os.path.join(unicode(QDesktopServices.storageLocation(QDesktopServices.DataLocation)), "Pesterchum/") elif isLinux(): return os.path.join(unicode(QDesktopServices.storageLocation(QDesktopServices.HomeLocation)), ".pesterchum/") else: return os.path.join(unicode(QDesktopServices.storageLocation(QDesktopServices.DataLocation)), "pesterchum/") except UnicodeDecodeError: return ''
def __init__(self, parent=None): QObject.__init__(self, parent) # variable declarations self.m_paperSize = {} self.m_clipRect = QRect() self.m_libraryPath = '' self.setObjectName('WebPage') self.m_webPage = CustomPage(self) self.m_mainFrame = self.m_webPage.mainFrame() self.m_webPage.loadStarted.connect(self.loadStarted) self.m_webPage.loadFinished.connect(self.finish) # Start with transparent background palette = self.m_webPage.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_webPage.setPalette(palette) # Page size does not need to take scrollbars into account self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) self.m_webPage.settings().setAttribute( QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_webPage.settings().setOfflineStoragePath( QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_webPage.settings().setAttribute( QWebSettings.LocalStorageDatabaseEnabled, True) self.m_webPage.settings().setAttribute( QWebSettings.OfflineWebApplicationCacheEnabled, True) self.m_webPage.settings().setOfflineWebApplicationCachePath( QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_webPage.settings().setAttribute( QWebSettings.FrameFlatteningEnabled, True) self.m_webPage.settings().setAttribute( QWebSettings.LocalStorageEnabled, True) self.m_webPage.settings().setLocalStoragePath( QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_webPage.mainFrame().setHtml('<html><body></body></html>') self.m_webPage.setViewportSize(QSize(400, 300)) do_action('WebPageInit', Bunch(locals()))
def restore_state(self): settings = QSettings() if not settings.contains('windowGeometry') or\ not settings.contains('windowState'): self.set_initial_layout() else: self.restoreGeometry(settings.value('windowGeometry')) self.restoreState(settings.value('windowState')) if not settings.contains('pluginPaths'): if hasattr(sys, 'frozen'): module_path = os.path.dirname(sys.executable) else: file_path = os.path.abspath(os.path.dirname(__file__)) module_path = os.path.dirname(os.path.dirname(file_path)) plugin_path = os.path.join(module_path, 'plugins') if os.path.isdir(plugin_path): self.plugin_paths.append(plugin_path) else: paths = settings.value('pluginPaths') if paths is None: self.plugin_paths = [] else: self.plugin_paths = paths if not settings.contains('selectionPath'): data_path = QDesktopServices.storageLocation( QDesktopServices.DataLocation) self.selection_path = os.path.join(data_path, 'selections') else: self.selection_path = settings.value('selectionPath') if not settings.contains('dataPath'): data_path = QDesktopServices.storageLocation( QDesktopServices.DataLocation) AnalysisPlugin.data_dir = os.path.join(data_path, 'data') else: AnalysisPlugin.data_dir = settings.value('dataPath') if not settings.contains('remoteScript'): if hasattr(sys, 'frozen'): path = os.path.dirname(sys.executable) else: file_path = os.path.abspath(os.path.dirname(__file__)) path = os.path.dirname(os.path.dirname(file_path)) path = os.path.join(path, 'bin') self.remote_script = os.path.join(path, 'spykeview_analysis') else: self.remote_script = settings.value('remoteScript')
def __init__(self): settings_folder = str(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) if not os.path.isdir(settings_folder): os.makedirs(settings_folder) settings_path = os.path.join(settings_folder, 'settings.ini') print settings_path self.settings = QSettings(settings_path, QSettings.IniFormat)
def open_scheme_on_new_window(self): """Open a new scheme. Return QDialog.Rejected if the user canceled the operation and QDialog.Accepted otherwise. """ document = self.current_document() if document.isModifiedStrict(): if self.ask_save_changes() == QDialog.Rejected: return QDialog.Rejected if self.last_scheme_dir is None: # Get user 'Documents' folder start_dir = QDesktopServices.storageLocation( QDesktopServices.DocumentsLocation) else: start_dir = self.last_scheme_dir # TODO: Use a dialog instance and use 'addSidebarUrls' to # set one or more extra sidebar locations where Schemes are stored. # Also use setHistory filename = QFileDialog.getOpenFileName( self, self.tr("Open Orange Workflow File"), start_dir, self.tr("Orange Workflow (*.ows)"), ) if filename: return self.load_scheme_on_window(filename, self.instantiate_window()) else: return QDialog.Rejected
def __init__(self): QObject.__init__(self) self.experimentResults = [] self.resultPath = os.path.join(str(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)),'EmcTestbench/') if not os.path.exists(self.resultPath): os.mkdir(self.resultPath)
def on_actionExportASCII_triggered(self): fname = self.filename if self.filename is None: home = QDesktopServices.HomeLocation fname = QDesktopServices.storageLocation(home) fname = os.path.join(str(fname), 'Untitled.txt') if os.path.splitext(fname)[-1] == '.brp': fname = os.path.splitext(fname)[0] + '.txt' props = self.songProperties self._asciiSettings = props.generateAsciiSettings(self._asciiSettings) asciiDialog = QAsciiExportDialog(fname, parent = self, settings = self._asciiSettings) if not asciiDialog.exec_(): return fname = asciiDialog.getFilename() self._asciiSettings = asciiDialog.getOptions() try: asciiBuffer = StringIO() exporter = AsciiExport.Exporter(self.scoreScene.score, self._asciiSettings) exporter.export(asciiBuffer) except StandardError: QMessageBox.warning(self.parent(), "ASCII generation failed!", "Could not generate ASCII for this score!") raise try: with open(fname, 'w') as txtHandle: txtHandle.write(asciiBuffer.getvalue()) except StandardError: QMessageBox.warning(self.parent(), "Export failed!", "Could not export to " + fname) raise else: self.updateStatus("Successfully exported ASCII to " + fname)
def _getFileName(self): directory = self.filename if directory is None: suggestion = unicode(self.scoreScene.title) if len(suggestion) == 0: suggestion = "Untitled" suggestion = os.extsep.join([suggestion, "brp"]) if len(self.recentFiles) > 0: directory = os.path.dirname(self.recentFiles[-1]) else: home = QDesktopServices.HomeLocation directory = unicode(QDesktopServices.storageLocation(home)) directory = os.path.join(directory, suggestion) if os.path.splitext(directory)[-1] == os.extsep + 'brp': directory = os.path.splitext(directory)[0] caption = "Choose a DrumBurp file to save" fname = QFileDialog.getSaveFileName(parent = self, caption = caption, directory = directory, filter = "DrumBurp files (*.brp)") if len(fname) == 0 : return False self.filename = unicode(fname) return True
def open_scheme_on_new_window(self): """Open a new scheme. Return QDialog.Rejected if the user canceled the operation and QDialog.Accepted otherwise. """ document = self.current_document() if document.isModifiedStrict(): if self.ask_save_changes() == QDialog.Rejected: return QDialog.Rejected if self.last_scheme_dir is None: # Get user 'Documents' folder start_dir = QDesktopServices.storageLocation( QDesktopServices.DocumentsLocation) else: start_dir = self.last_scheme_dir # TODO: Use a dialog instance and use 'addSidebarUrls' to # set one or more extra sidebar locations where Schemes are stored. # Also use setHistory filename = QFileDialog.getOpenFileName( self, self.tr("Open Orange Workflow File"), start_dir, self.tr("Orange Workflow (*.ows)"), ) if filename: return self.load_scheme_on_window(filename, self.instantiate_window()) else: return QDialog.Rejected
def __init__(self, parent, args): super(NetworkAccessManager, self).__init__(parent) self.m_userName = self.m_password = '' self.m_ignoreSslErrors = args.ignore_ssl_errors self.m_idCounter = 0 self.m_ids = {} self.m_started = [] if args.cookies_file: self.setCookieJar(CookieJar(self, args.cookies_file)) if args.disk_cache: m_networkDiskCache = QNetworkDiskCache() m_networkDiskCache.setCacheDirectory( QDesktopServices.storageLocation( QDesktopServices.CacheLocation)) if args.max_disk_cache_size > 0: m_networkDiskCache.setMaximumCacheSize( args.max_disk_cache_size * 1024) self.setCache(m_networkDiskCache) self.authenticationRequired.connect(self.provideAuthentication) self.finished.connect(self.handleFinished) do_action('NetworkAccessManagerInit')
def __saveScreenshot(self): format = "png" initialPath = QDesktopServices.storageLocation( QDesktopServices.PicturesLocation) # initialPath = QStandardPaths::writableLocation(QStandardPaths::PicturesLocation); if initialPath.isEmpty(): initialPath = QDir.currentPath() initialPath += "/untitled." + format fileDialog = QtGui.QFileDialog(self, u"存储为", initialPath) fileDialog.setAcceptMode(QtGui.QFileDialog.AcceptSave) fileDialog.setFileMode(QtGui.QFileDialog.AnyFile) fileDialog.setDirectory(initialPath) mimeTypes = QStringList() for bf in QImageWriter.supportedImageFormats(): mimeTypes.append(QLatin1String(bf)) # fileDialog.setMin setMimeTypeFilters(mimeTypes) # fileDialog.selectMimeTypeFilter("image/" + format); fileDialog.setDefaultSuffix(format) if fileDialog.accept(): return fileName = fileDialog.selectedFiles().first() if not self.originalPixmap.save(fileName): QtGui.QMessageBox.Warning( self, u"保存错误", u"图像无法存储到 \"%s\"." % str(QDir.toNativeSeparators(fileName)))
def getInputFile(self, startpath=str( QDesktopServices.storageLocation( QDesktopServices.HomeLocation)), model=None): '''returns file path of input''' if model == None: model = '' else: model += ' ' model = model.capitalize() # start at last known directory if os.path.exists(self.lastpath): if os.path.isfile(self.lastpath): startpath = os.path.dirname(self.lastpath) else: startpath = self.lastpath filepath = str( QFileDialog.getOpenFileName(parent=None, caption='Open %sInput File' % model, directory=startpath)) return filepath
def getPathToStorage(self): """Return the path to a place for writing supporting files""" path = unicode( QDesktopServices.storageLocation(QDesktopServices.DataLocation)) if not isdir(path): makedirs(path) return path
def get(name): """ Retrieve setting and convert result """ home_dir = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) stdPwlDict = unicode(home_dir + QDir.separator() + "my-dict.txt") settings = QSettings("Davide Setti", "Lector") if name == 'scanner:height': return settings.value(name, QVariant(297)).toInt()[0] elif name == 'scanner:width': return settings.value(name, QVariant(210)).toInt()[0] elif name == 'scanner:resolution': return settings.value(name, QVariant(300)).toInt()[0] elif name == 'scanner:mode': return str(settings.value(name, QVariant("Color")).toString()) elif name == 'scanner:device': return str(settings.value(name).toString()) elif name == 'editor:font': return settings.value(name, QFont(QFont("Courier New", 10))) elif name == 'editor:symbols': return settings.value(name).toString() elif name in ('editor:clear', 'editor:spell', 'editor:whiteSpace', 'spellchecker:pwlLang',): return str(settings.value(name, "true").toString()).lower() == "true" elif name in ('log:errors'): return str(settings.value(name, "false").toString()).lower() == "true" elif name == 'spellchecker:pwlDict': return str(settings.value(name, stdPwlDict).toString()) else: return str(settings.value(name).toString())
def __init__(self): ApplicationBase.__init__(self) self.prefs = Preferences() self.prefs.load() global APP_PREFS APP_PREFS = self.prefs locale = QLocale.system() dateFormat = self.prefs.dateFormat decimalSep = locale.decimalPoint() groupingSep = locale.groupSeparator() cachePath = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) appdata = getAppData() plugin_model_path = op.join(BASE_PATH, 'plugin_examples') DateEdit.DATE_FORMAT = dateFormat self.model = MoneyGuruModel( view=self, date_format=dateFormat, decimal_sep=decimalSep, grouping_sep=groupingSep, cache_path=cachePath, appdata_path=appdata, plugin_model_path=plugin_model_path ) # on the Qt side, we're single document based, so it's one doc per app. self.doc = Document(app=self) self.doc.model.connect() self.mainWindow = MainWindow(doc=self.doc) self.preferencesPanel = PreferencesPanel(self.mainWindow, app=self) self.aboutBox = AboutBox(self.mainWindow, self) if sys.argv[1:] and op.exists(sys.argv[1]): self.doc.open(sys.argv[1]) elif self.prefs.recentDocuments: self.doc.open(self.prefs.recentDocuments[0]) self.connect(self, SIGNAL('applicationFinishedLaunching()'), self.applicationFinishedLaunching) QCoreApplication.instance().aboutToQuit.connect(self.applicationWillTerminate)
def __init__(self): self.startMoment = datetime.datetime.now() super(QualifySwitchMeasurement, self).__init__() self.vna = knownDevices["networkAnalyzer"] self.switch = knownDevices["switchPlatform"] self.vna.putOnline() self.switch.putOnline() self.qualificationDirectory = os.path.join( str(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)), "EmcTestbench/Qualification/L4490 " + self.startMoment.strftime("%Y-%m-%d %H%M%S"), ) os.mkdir(self.qualificationDirectory) os.mkdir(self.connectionsDirectory) self.metadata.add_section("operation") self.metadata.set("operation", "startMoment", self.startMoment.isoformat()) self.metadata.set("operation", "operator", prompt("Please enter your name:")) self.metadata.set("operation", "scriptFile", debugging.currentFile()) self.metadata.add_section("equipment") self.metadata.set("equipment", "vna", self.vna.detailedInformation) self.metadata.set("equipment", "switchPlatform", self.switch.detailedInformation) self.metadata.add_section("calibration") self.metadata.set("calibration", "calibrationKit", prompt("Please enter the used calibration kit:")) self.metadata.set( "calibration", "calibrationNotes", prompt( "Please enter other notes on the calibration (cables used, added offset, resulting reference plane:" ), )
def on_actionExportASCII_triggered(self): fname = self.filename if self.filename is None: home = QDesktopServices.HomeLocation fname = QDesktopServices.storageLocation(home) fname = os.path.join(str(fname), 'Untitled.txt') if os.path.splitext(fname)[-1] == '.brp': fname = os.path.splitext(fname)[0] + '.txt' props = self.songProperties self._asciiSettings = props.generateAsciiSettings(self._asciiSettings) asciiDialog = QAsciiExportDialog(fname, parent=self, settings=self._asciiSettings) if not asciiDialog.exec_(): return fname = asciiDialog.getFilename() self._asciiSettings = asciiDialog.getOptions() try: asciiBuffer = StringIO() exporter = AsciiExport.Exporter(self.scoreScene.score, self._asciiSettings) exporter.export(asciiBuffer) except StandardError: QMessageBox.warning(self.parent(), "ASCII generation failed!", "Could not generate ASCII for this score!") raise try: with open(fname, 'w') as txtHandle: txtHandle.write(asciiBuffer.getvalue()) except StandardError: QMessageBox.warning(self.parent(), "Export failed!", "Could not export to " + fname) raise else: self.updateStatus("Successfully exported ASCII to " + fname)
def _getDefaultFileOpenDir(self, settings): ':type settings:QSettings' openDir = settings.value('lastUsedFileOpenDir', '') if not openDir: absoluteProjectPath = QgsProject.instance().readPath("./") openDir = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) if absoluteProjectPath == "./" else absoluteProjectPath return openDir
def get(name): """ Retrieve setting and convert result """ home_dir = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) stdPwlDict = unicode(home_dir + QDir.separator() + "my-dict.txt") settings = QSettings("Davide Setti", "Lector") if name == 'scanner:height': return settings.value(name, QVariant(297)).toInt()[0] elif name == 'scanner:width': return settings.value(name, QVariant(210)).toInt()[0] elif name == 'scanner:resolution': return settings.value(name, QVariant(300)).toInt()[0] elif name == 'scanner:mode': return str(settings.value(name, QVariant("Color")).toString()) elif name == 'scanner:device': return str(settings.value(name).toString()) elif name == 'editor:font': return settings.value(name, QFont(QFont("Courier New", 10))) elif name == 'editor:symbols': return settings.value(name).toString() elif name in ( 'editor:clear', 'editor:spell', 'editor:whiteSpace', 'spellchecker:pwlLang', ): return str(settings.value(name, "true").toString()).lower() == "true" elif name in ('log:errors'): return str(settings.value(name, "false").toString()).lower() == "true" elif name == 'spellchecker:pwlDict': return str(settings.value(name, stdPwlDict).toString()) else: return str(settings.value(name).toString())
def __init__(self, parent, args): super(WebPage, self).__init__(parent) # variable declarations self.m_paperSize = {} self.m_clipRect = QRect() self.m_libraryPath = '' self.m_scrollPosition = QPoint() self.setObjectName('WebPage') self.m_webPage = CustomPage(self) self.m_mainFrame = self.m_webPage.mainFrame() self.m_mainFrame.javaScriptWindowObjectCleared.connect(self.initialized) self.m_webPage.loadStarted.connect(self.loadStarted) self.m_webPage.loadFinished.connect(self.finish) # Start with transparent background palette = self.m_webPage.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_webPage.setPalette(palette) # Page size does not need to take scrollbars into account self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) self.m_webPage.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_webPage.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True) self.m_webPage.settings().setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True) self.m_webPage.settings().setOfflineWebApplicationCachePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_webPage.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_webPage.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_webPage.mainFrame().setHtml(self.blankHtml) # Custom network access manager to allow traffic monitoring self.m_networkAccessManager = NetworkAccessManager(self.parent(), args) self.m_webPage.setNetworkAccessManager(self.m_networkAccessManager) self.m_networkAccessManager.resourceRequested.connect(self.resourceRequested) self.m_networkAccessManager.resourceReceived.connect(self.resourceReceived) self.m_webPage.setViewportSize(QSize(400, 300)) do_action('WebPageInit')
def _default_directory(settings): current_directory = settings.value('lastUsedFileOpenDir', '') if not current_directory: absolute_project_path = QgsProject.instance().readPath("./") current_directory = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) \ if absolute_project_path == "./" \ else absolute_project_path return current_directory
def __init__(self, diskCacheEnabled, parent = None): QNetworkAccessManager.__init__(self, parent) self.connect(self, SIGNAL('finished(QNetworkReply *)'), self.handleFinished) if diskCacheEnabled == 'yes': m_networkDiskCache = QNetworkDiskCache() m_networkDiskCache.setCacheDirectory(QDesktopServices.storageLocation(QDesktopServices.CacheLocation)) self.setCache(m_networkDiskCache)
def get_music_storage_folder(): storage_path = "%s%s%s" % (QDesktopServices.storageLocation(QDesktopServices.DataLocation).replace("\\", "/"), Config.DataPrefix, Config.MusicPrefix) dir = QDir(storage_path) if dir.exists() != True: dir.mkpath('.') return storage_path
def __init__(self, diskCacheEnabled, parent = None): QNetworkAccessManager.__init__(self, parent) self.finished.connect(self.handleFinished) if diskCacheEnabled == 'yes': m_networkDiskCache = QNetworkDiskCache() m_networkDiskCache.setCacheDirectory(QDesktopServices.storageLocation(QDesktopServices.CacheLocation)) self.setCache(m_networkDiskCache)
def setDefaultScreenshotDir(self): path = join( unicode( QDesktopServices.storageLocation( QDesktopServices.PicturesLocation)), "Frontier Developments", "Elite Dangerous") self.reg.setValue('screenshot_dir', isdir(path) and path or self.userprofile)
def set_cache(self, cache_size_in_mb=100): cache = QtNetwork.QNetworkDiskCache() location = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) cache.setCacheDirectory(os.path.join(unicode(location), u"picard")) cache.setMaximumCacheSize(cache_size_in_mb * 1024 * 1024) self.manager.setCache(cache) log.debug("NetworkDiskCache dir: %s", cache.cacheDirectory()) log.debug("NetworkDiskCache size: %s / %s", cache.cacheSize(), cache.maximumCacheSize())
def _default_base(self): if isWin: loc = QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation) return os.path.join(unicode(loc), "Natural Order Japanese") elif isMac: return os.path.expanduser("~/Documents/Natural Order Japanese") else: return os.path.expanduser("~/Natural Order Japanese")
def __init__(self, directory=None, maxSize=104857600, parent=None): QNetworkDiskCache.__init__(self, parent=parent) if directory is None: directory = str(QDesktopServices.storageLocation(QDesktopServices.CacheLocation)) self.setMaximumCacheSize(maxSize) self.setCacheDirectory(directory)
def runShortcut(self, index): if not index.isValid(): return False shortcut = self.shortcuts[index.row()] if shortcut["path"].startswith("special://"): if shortcut["path"] == COMPUTER_PATH: if os.name == "nt": explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe") return QProcess.startDetached(explorer, ["::{20D04FE0-3AEA-1069-A2D8-08002B30309D}"]) else: path = "/" elif shortcut["path"] == DOCUMENTS_PATH: path = QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation) elif shortcut["path"] == MUSIC_PATH: path = QDesktopServices.storageLocation(QDesktopServices.MusicLocation) elif shortcut["path"] == PICTURES_PATH: path = QDesktopServices.storageLocation(QDesktopServices.PicturesLocation) else: return False if os.name == "nt": #针对windows进行优化 explorer = os.path.join(os.environ["SystemRoot"], "explorer.exe") return QProcess.startDetached(explorer, [path]) else: return QDesktopServices.openUrl(QUrl.fromLocalFile(path)) else: currentDirectory = os.getcwd() try: if shortcut["dir"] is not None and shortcut["dir"] != "": os.chdir(shortcut["dir"]) if shortcut["openwith"] is not None and shortcut["openwith"] != "": if not os.path.exists(shortcut["openwith"]): return False return QProcess.startDetached(shortcut["openwith"], [shortcut["path"]]) else: url = QUrl.fromUserInput(shortcut["path"]) if not url.isValid(): return False if url.scheme() == "file" and not os.path.exists(url.toLocalFile()): return False return QDesktopServices.openUrl(url) except OSError: #raised by chdir() pass finally: os.chdir(currentDirectory) return False
def __init__(self, parent): QObject.__init__(self, parent) self.m_parent = parent # variable declarations self.m_paperSize = {} self.m_clipRect = QRect() self.m_libraryPath = "" self.m_mousePos = QPoint() self.setObjectName("WebPage") self.m_webPage = CustomPage(self) self.m_mainFrame = self.m_webPage.mainFrame() self.m_mainFrame.javaScriptWindowObjectCleared.connect(self.initialized) self.m_webPage.loadStarted.connect(self.loadStarted) self.m_webPage.loadFinished.connect(self.finish) # Start with transparent background palette = self.m_webPage.palette() palette.setBrush(QPalette.Base, Qt.transparent) self.m_webPage.setPalette(palette) # Page size does not need to take scrollbars into account self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Horizontal, Qt.ScrollBarAlwaysOff) self.m_webPage.mainFrame().setScrollBarPolicy(Qt.Vertical, Qt.ScrollBarAlwaysOff) self.m_webPage.settings().setAttribute(QWebSettings.OfflineStorageDatabaseEnabled, True) self.m_webPage.settings().setOfflineStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageDatabaseEnabled, True) self.m_webPage.settings().setAttribute(QWebSettings.OfflineWebApplicationCacheEnabled, True) self.m_webPage.settings().setOfflineWebApplicationCachePath( QDesktopServices.storageLocation(QDesktopServices.DataLocation) ) self.m_webPage.settings().setAttribute(QWebSettings.FrameFlatteningEnabled, True) self.m_webPage.settings().setAttribute(QWebSettings.LocalStorageEnabled, True) self.m_webPage.settings().setLocalStoragePath(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) # Ensure we have a document.body. self.m_webPage.mainFrame().setHtml("<html><body></body></html>") self.m_webPage.setViewportSize(QSize(400, 300)) do_action("WebPageInit")
def set_cache(self, cache_size_in_mb=100): cache = QtNetwork.QNetworkDiskCache() location = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) cache.setCacheDirectory(os.path.join(unicode(location), u'picard')) cache.setMaximumCacheSize(cache_size_in_mb * 1024 * 1024) self.manager.setCache(cache) log.debug("NetworkDiskCache dir: %s", cache.cacheDirectory()) log.debug("NetworkDiskCache size: %s / %s", cache.cacheSize(), cache.maximumCacheSize())
def save_configuration(): """ A util method for saving the configuration instance to the default file location. """ config_path = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) \ + '/.stdm/configuration.stc' conf_serializer = ConfigurationFileSerializer(config_path) conf_serializer.save()
def save_configuration(): """ A util method for saving the configuration instance to the default file location. """ config_path = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) \ + '/.stdm/configuration.stc' conf_serializer = ConfigurationFileSerializer(config_path) conf_serializer.save()
def addFiles(self): print("addFiles") files = QFileDialog.getOpenFileNames(self, "Select Music Files", QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation)) if not files: return self.files_paths_list = files print "len_list = {0}".format(len(self.files_paths_list)) self.refresh_files_table()
def __init__(self, proxy, forbidden_extensions, allowed_regex, cache_size=100, cache_dir='.webkit_cache'): """ See WebkitBrowser for details of arguments cache_size: the maximum size of the webkit cache (MB) """ QNetworkAccessManager.__init__(self) # and proxy self.setProxy(proxy) # initialize the manager cache QDesktopServices.storageLocation(QDesktopServices.CacheLocation) cache = QNetworkDiskCache() cache.setCacheDirectory(cache_dir) cache.setMaximumCacheSize(cache_size * 1024 * 1024) # need to convert cache value to bytes self.setCache(cache) self.allowed_regex = allowed_regex self.forbidden_extensions = forbidden_extensions
def _default_directory(settings): current_directory = settings.value("lastUsedFileOpenDir", "") if not current_directory: absolute_project_path = QgsProject.instance().readPath("./") current_directory = ( QDesktopServices.storageLocation(QDesktopServices.HomeLocation) if absolute_project_path == "./" else absolute_project_path ) return current_directory
def cache_dir(): """Return the application cache directory. If the directory path does not yet exists then create it. """ init() cachedir = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) cachedir = str(cachedir) if not os.path.exists(cachedir): os.makedirs(cachedir) return cachedir
def cache_dir(): """Return the application cache directory. If the directory path does not yet exists then create it. """ init() cachedir = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) cachedir = unicode(cachedir) if not os.path.exists(cachedir): os.makedirs(cachedir) return cachedir
def data_dir(): """Return the application data directory. If the directory path does not yet exists then create it. """ init() datadir = QDesktopServices.storageLocation(QDesktopServices.DataLocation) datadir = unicode(datadir) if not os.path.exists(datadir): os.makedirs(datadir) return datadir
def addFiles(self): print("addFiles") files = QFileDialog.getOpenFileNames( self, "Select Music Files", QDesktopServices.storageLocation( QDesktopServices.DocumentsLocation)) if not files: return self.files_paths_list = files print "len_list = {0}".format(len(self.files_paths_list)) self.refresh_files_table()
def data_dir(): """Return the application data directory. If the directory path does not yet exists then create it. """ init() datadir = QDesktopServices.storageLocation(QDesktopServices.DataLocation) datadir = str(datadir) if not os.path.exists(datadir): os.makedirs(datadir) return datadir
def main(): """Test module functionality """ print 'starting tests...' home_dir = QDesktopServices.storageLocation(QDesktopServices.HomeLocation) print 'Home dir is:', home_dir print 'configFile:', configFile() print 'Input durectory is: ', readSetting('images/input_dir') print 'Last used filename is: ', readSetting('images/last_filename') print 'language:', readSetting('language'), type(readSetting('language')), print 'tests ended...'
def data_dir(): """Return the application data directory. If the directory path does not yet exists then create it. """ import Orange init() datadir = QDesktopServices.storageLocation(QDesktopServices.DataLocation) datadir = str(datadir) datadir = os.path.join(datadir, Orange.__version__) if not os.path.exists(datadir): os.makedirs(datadir) return datadir
def getPathToStorage(self): """Return the path to a place for writing supporting files""" if platform == 'win32': path = join( self.getPathToSelf(), "trainingdata") # Store writable data alongside executable else: path = unicode( QDesktopServices.storageLocation( QDesktopServices.DataLocation)) if not isdir(path): makedirs(path) return path
def getDataDir(): # Temporary fix for non-ascii usernames # If username has non-ascii characters, just store userdata # in the Pesterchum install directory (like before) try: if isOSX(): return os.path.join( unicode( QDesktopServices.storageLocation( QDesktopServices.DataLocation)), "Pesterchum/") elif isLinux(): return os.path.join( unicode( QDesktopServices.storageLocation( QDesktopServices.HomeLocation)), ".pesterchum/") else: return os.path.join( unicode( QDesktopServices.storageLocation( QDesktopServices.DataLocation)), "pesterchum/") except UnicodeDecodeError: return ''
def cache_dir(): """Return the application cache directory. If the directory path does not yet exists then create it. """ import Orange init() cachedir = QDesktopServices.storageLocation(QDesktopServices.CacheLocation) cachedir = str(cachedir) cachedir = os.path.join(cachedir, Orange.__version__) if not os.path.exists(cachedir): os.makedirs(cachedir) return cachedir
def __init__(self, diskCacheEnabled, ignoreSslErrors, parent=None): QNetworkAccessManager.__init__(self, parent) self.m_ignoreSslErrors = ignoreSslErrors if parent.m_verbose: self.finished.connect(self.handleFinished) if diskCacheEnabled == 'yes': m_networkDiskCache = QNetworkDiskCache() m_networkDiskCache.setCacheDirectory(QDesktopServices.storageLocation(QDesktopServices.CacheLocation)) self.setCache(m_networkDiskCache) do_action('NetworkAccessManagerInit', Bunch(locals()))
def get_default_storage(cls): """ :return: a camelot.core.files.storage.Storage object Returns the storage to be used to store default backups. By default, this will return a Storage that puts the backup files in the DataLocation as specified by the QDesktopServices """ from PyQt4.QtGui import QDesktopServices apps_folder = unicode(QDesktopServices.storageLocation(QDesktopServices.DataLocation)) from camelot.core.files.storage import Storage return Storage(upload_to='backups', root=apps_folder)
def getShortcutIcon(shortcut): if shortcut["icon"]: icon = QIcon(shortcut["icon"]) if not icon.isNull(): return icon iconProvider = QFileIconProvider() if shortcut["path"] == COMPUTER_PATH: return QIcon(":/images/user-home.png") elif shortcut["path"] == DOCUMENTS_PATH: documentsIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.DocumentsLocation))) if documentsIcon.isNull(): return QIcon(":/images/folder-documents.png") else: return documentsIcon elif shortcut["path"] == MUSIC_PATH: musicIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.MusicLocation))) if musicIcon.isNull(): return QIcon(":/images/folder-sound.png") else: return musicIcon elif shortcut["path"] == PICTURES_PATH: picturesIcon = iconProvider.icon(QFileInfo(QDesktopServices.storageLocation(QDesktopServices.PicturesLocation))) if picturesIcon.isNull(): return QIcon(":/images/folder-image.png") else: return picturesIcon else: url = QUrl.fromUserInput(shortcut["path"]) if url.scheme() == "file": if os.path.exists(shortcut["path"]): icon = iconProvider.icon(QFileInfo(url.toLocalFile())) if not icon.isNull(): return icon return QIcon(":/images/unknown.png") else: return QIcon(":/images/httpurl.png") return QIcon(":/images/unknown.png")
def __init__(self, title='Plugin Editor', default_path=None, parent=None): QDockWidget.__init__(self, title, parent) self.setupUi() self.thread_manager = ThreadManager(self) try: self.rope_project = codeeditor.get_rope_project() except (IOError, AttributeError): # Might happen when frozen self.rope_project = None data_path = QDesktopServices.storageLocation( QDesktopServices.DataLocation) self.default_path = default_path or os.getcwd() self.rope_temp_path = os.path.join(data_path, '.temp') self.tabs.currentChanged.connect(self._tab_changed) self.enter_completion = True
def _saveKit(self): directory = self._scoreDirectory if directory is None: home = QDesktopServices.HomeLocation directory = unicode(QDesktopServices.storageLocation(home)) fname = QFileDialog.getSaveFileName(parent=self, caption="Save DrumBurp kit", directory=directory, filter=_KIT_FILTER) if len(fname) == 0: return fname = unicode(fname) newKit, unused = self.getNewKit() DrumKitSerializer.DrumKitSerializer.saveKit(newKit, fname) QMessageBox.information(self, "Kit saved", "Successfully saved drumkit")