我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtCore.QSettings()。
def __init__(self, parent, settings: QSettings, f=Qt.WindowCloseButtonHint): super(Settings, self).__init__(parent, f) self.parent = parent self.settings = settings self.setWindowModality(Qt.ApplicationModal) self.tab_general = GeneralTab(self.settings) self.tab_favorites = FavoritesTab(self.settings) tabs = QTabWidget() tabs.addTab(self.tab_general, 'General') tabs.addTab(self.tab_favorites, 'Favorites') button_box = QDialogButtonBox(QDialogButtonBox.Save | QDialogButtonBox.Cancel, Qt.Horizontal, self) button_box.accepted.connect(self.save_settings) button_box.rejected.connect(self.close) layout = QVBoxLayout() layout.addWidget(tabs) layout.addWidget(button_box) self.setLayout(layout) self.setWindowTitle('%s Settings' % qApp.applicationName()) self.setWindowIcon(self.parent.icon_settings)
def read_settings(self): self.settings = QtCore.QSettings('fume', 'Match-Explorer') self.resize(self.settings.value('mainwindow/size', self.size())) try: self.move(self.settings.value('mainwindow/pos')) except: pass self.actionZeitraum.setChecked(self.settings.value('menubar/date/range', True, bool)) self.actionZeitpunkt.setChecked(self.settings.value('menubar/date/day', False, bool)) now = datetime.datetime.now() self.dateEdit_3.setDate(self.settings.value('date_from_calendar', QtCore.QDate(now.year, now.month, now.day))) self.dateEdit_4.setDate(self.settings.value('date_to_calendar', QtCore.QDate(now.year, now.month, now.day))) # dbPaths # Windows: ?C:\Users\<User>\AppData\Local\FuME\FuME # macOS: /Users/<User>/Library/Application Support/FuME userDataDir = appdirs.user_data_dir('FuME', 'FuME') src = self.get_pathToTemp(['db', 'sql_default.db']) dst = os.path.join(userDataDir, 'sql.db') if not os.path.exists(userDataDir): os.makedirs(userDataDir) shutil.copy(src, dst) self.dbPath = dst
def __init__(self, data, parent=None): super(UpdateDialog, self).__init__(parent) self.setupUi(self) self.setModal(True) self.data = data self.label.setPixmap(QtGui.QPixmap(data['logo'])) self.settings = QtCore.QSettings('fume', 'Match-Explorer') self.wouldYouLikeToDownloadLabel.setText( "FuME {latest} ist verfügbar (Du verwendest Version {current}). " "Möchtest du die neue Version jetzt herunterladen?".format(current=data['current'], latest=data['latest'])) self.textEdit.setText(data['changelog']) # restore check state self.checkBox.setChecked(self.settings.value('updates/noautoupdate', False, bool)) # Connections self.skipThisVersionButton.clicked.connect(self.skipThisVersion) self.remindMeLaterButton.clicked.connect(self.close) self.installUpdateButton.clicked.connect(self.installUpdates) self.checkBox.stateChanged.connect(self.noAutoUpdates)
def read_settings(self): self.info("Reading settings") settings = QtCore.QSettings("sequana_gui", "mainapp") if settings.value("tab_position") is not None: index = settings.value("tab_position") self.ui.tabs_pipeline.setCurrentIndex(int(index)) if settings.value("tab_generic_position") is not None: index = settings.value("tab_generic_position") self.ui.tabs_generic.setCurrentIndex(int(index)) if settings.value("tab_sequana_position") is not None: index = settings.value("tab_sequana_position") self.ui.tabs_sequana.setCurrentIndex(int(index)) if settings.value("tab_sequana_input_position") is not None: index = settings.value("tab_sequana_input_position") self.ui.tabWidget.setCurrentIndex(int(index))
def read_settings(self): settings = QtCore.QSettings(self._application, self._section) for key in settings.allKeys(): value = settings.value(key) try: # This is required to skip the tab_position key/value this = getattr(self.ui, key) except: continue if isinstance(this, QW.QLineEdit): this.setText(value) elif isinstance(this, QW.QSpinBox): this.setValue(int(value)) elif isinstance(this, QW.QCheckBox): if value in ['false', False, "False"]: this.setChecked(False) else: this.setChecked(True) elif isinstance(this, FileBrowser): this.set_filenames(value) else: print('could not handle : %s' % this) # The last tab position self._tab_pos = settings.value("tab_position", 0, type=int) self.ui.tabs.setCurrentIndex(self._tab_pos)
def export_settings(settings, config_path): """ Export the given settings instance to the given file system path. type settings: IDASettingsInterface type config_path: str """ other = QtCore.QSettings(config_path, QtCore.QSettings.IniFormat) for k, v in settings.iteritems(): other.setValue(k, v) ####################################################################################### # # Test Cases # run this file as an IDAPython script to invoke the tests. # #######################################################################################
def setCurrentFile(self, fileName): self.curFile = fileName if self.curFile: self.setWindowTitle("%s - Recent Files" % self.strippedName(self.curFile)) else: self.setWindowTitle("Recent Files") settings = QSettings('Trolltech', 'Recent Files Example') files = settings.value('recentFileList', []) try: files.remove(fileName) except ValueError: pass files.insert(0, fileName) del files[MainWindow.MaxRecentFiles:] settings.setValue('recentFileList', files) for widget in QApplication.topLevelWidgets(): if isinstance(widget, MainWindow): widget.updateRecentFileActions()
def updateRecentFileActions(self): settings = QSettings('Trolltech', 'Recent Files Example') files = settings.value('recentFileList', []) numRecentFiles = min(len(files), MainWindow.MaxRecentFiles) for i in range(numRecentFiles): text = "&%d %s" % (i + 1, self.strippedName(files[i])) self.recentFileActs[i].setText(text) self.recentFileActs[i].setData(files[i]) self.recentFileActs[i].setVisible(True) for j in range(numRecentFiles, MainWindow.MaxRecentFiles): self.recentFileActs[j].setVisible(False) self.separatorAct.setVisible((numRecentFiles > 0))
def __init__(self, view): QObject.__init__(self, view) self.view = view self.model = TreeViewModel() self.model.clear() # FIXME: do we need this? self.model.error.connect(self.error) self.view.setModel(self.model) #self.view.setUniformRowHeights(True) self.model.setHorizontalHeaderLabels(['DisplayName', "BrowseName", 'NodeId']) self.view.header().setSectionResizeMode(0) self.view.header().setStretchLastSection(True) self.view.setSelectionBehavior(QAbstractItemView.SelectRows) self.settings = QSettings() state = self.settings.value("tree_widget_state", None) if state is not None: self.view.header().restoreState(state) self.actionReload = QAction("Reload", self) self.actionReload.triggered.connect(self.reload_current)
def __init__(self): colorSchemName = QtCore.QSettings().value("color_schem", "") if str(colorSchemName).find("dark") >= 0: # for dark theme self.priority_colors = dict(A='red', B='#1C7F61', C='#7397BE') self.contextColor = "#5ED2B8" self.projectColor = "#FFCA73" self.priorityDuecolors = ['red', '#E0A180'] self.priorityThresholdColors = ['orange', 'grey'] self.errorColor = "red" self.linkColor = "#E0A180" else: # for light theme self.priority_colors = dict(A='red', B='green', C='navy') self.contextColor = "green" self.projectColor = "#64AAD0" self.priorityDuecolors = ['red', 'orange'] self.priorityThresholdColors = ['orange', 'grey'] self.errorColor = "red" self.linkColor = "none" self.complColor = "gray"
def __init__(self, args): super(MainController, self).__init__() self._args = args self._filteredTasks = [] self._sortingMode = "default" # use object variable for setting only used in this class # others are accessed through QSettings self._settings = QtCore.QSettings() self._file = File() self._file.fileExternallyModified.connect(self.fileExternallyModified) self._file.fileModified.connect(self._fileModified) self.filtersController = FiltersController() self._title = "QTodoTxt" self._recentFiles = self._settings.value("recent_files", []) self._updateCompletionStrings() self._forced = None
def load_classifyhub_settings(): settings = QSettings() old_config = configserver.get_config() configserver.parse_args() for key in old_config.keys(): if configserver.get(key) == old_config[key]: # This key wasn't changed by cmd arguments - so try to load it from config data = configserver.get(key) if isinstance(data, bool): configserver.set(key, bool(int(settings.value('classifyhub/{}'.format(key), old_config[key])))) elif isinstance(data, int): configserver.set(key, int(settings.value('classifyhub/{}'.format(key), old_config[key]))) elif isinstance(data, str): configserver.set(key, str(settings.value('classifyhub/{}'.format(key), old_config[key]))) else: # Save cmd options so no confusion will occur for user settings.setValue('classifyhub/{}'.format(key), configserver.get(key))
def getSettings(self): portable_fn = PROGRAM_NAME + '.ini' portable_fn = os.path.join(_basedir, portable_fn) if os.path.exists(portable_fn): return QtCore.QSettings( portable_fn, QtCore.QSettings.IniFormat ) return QtCore.QSettings( QtCore.QSettings.IniFormat, QtCore.QSettings.UserScope, PROGRAM_NAME, PROGRAM_NAME )
def __init__(self, settings: QSettings): super(FavoritesTab, self).__init__() self.settings = settings faves_formLayout = QFormLayout(labelAlignment=Qt.AlignRight) self.faves_lineEdit = QLineEdit(self) self.faves_lineEdit.returnPressed.connect(self.add_item) self.faves_lineEdit.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Fixed) faves_addItemButton = QPushButton(parent=self, flat=False, cursor=Qt.PointingHandCursor, text='Add', icon=QIcon(':assets/images/plus.png'), toolTip='Add item', clicked=self.add_item) faves_addItemButton.setIconSize(QSize(12, 12)) faves_deleteItemButton = QPushButton(parent=self, flat=False, cursor=Qt.PointingHandCursor, text='Delete', icon=QIcon(':assets/images/minus.png'), toolTip='Delete selected item', clicked=self.delete_items) faves_deleteItemButton.setIconSize(QSize(12, 12)) faves_buttonLayout = QHBoxLayout() faves_buttonLayout.addWidget(faves_addItemButton) faves_buttonLayout.addWidget(faves_deleteItemButton) faves_formLayout.addRow('Item Label:', self.faves_lineEdit) faves_formLayout.addRow(faves_buttonLayout) faves_formLayout.addRow(self.get_notes()) self.faves_listWidget = QListWidget(self) self.faves_listWidget.setSelectionMode(QAbstractItemView.ExtendedSelection) self.faves_listWidget.setSortingEnabled(True) self.add_items(self.settings.value('favorites', '')) tab_layout = QHBoxLayout() tab_layout.addLayout(faves_formLayout) tab_layout.addWidget(self.faves_listWidget) self.setLayout(tab_layout)
def __init__(self, settings: QSettings, api_url: str, link_url: str, action: RealDebridAction = RealDebridAction.UNRESTRICT_LINK, check_host: str = None): QThread.__init__(self) self.api_url = api_url self.api_token = settings.value('realdebrid_apitoken') self.link_url = link_url self.action = action self.check_host = check_host self.proxy = ShadowSocks.proxy()
def __init__(self, settings: QSettings, link_url: str): QThread.__init__(self) self.rpc_host = settings.value('aria2_rpc_host') self.rpc_port = settings.value('aria2_rpc_port') self.rpc_secret = settings.value('aria2_rpc_secret') self.rpc_username = settings.value('aria2_rpc_username') self.rpc_password = settings.value('aria2_rpc_password') self.link_url = link_url
def __init__(self, options): super(ReserveProcessor, self).__init__(options['parent']) self.settings = QtCore.QSettings('fume', 'Match-Explorer') self.options = options self.selected = options['selected'] self.cookies = options['cookie'] self.dbPath = options['database-path'] self.baseUrl = 'https://www.fupa.net/fupa/admin/index.php?page=fotograf_spiele' # def __del__(self): # self.wait()
def __init__(self, options): super(GaleryProcessor, self).__init__(options['parent']) self.settings = QtCore.QSettings('fume', 'Match-Explorer') self.match = options['match'] self.files = options['files'] self.cookies = options['cookies'] self.baseUrl = 'https://www.fupa.net/fupa/admin/index.php?page=fotograf_spiele' # def __del__(self): # self.wait()
def __init__(self, parent=None): super(SettingsDialog, self).__init__(parent) self.setupUi(self) self.setModal(True) self.settings = QtCore.QSettings('fume', 'Match-Explorer') self.checkBox.setChecked(self.settings.value('chrome/headless', True, bool)) # Connections self.pushButton.clicked.connect(self.createCookie) self.pushButton_2.clicked.connect(self.deleteSettings) self.pushButton_3.clicked.connect(self.deleteDatabase) self.checkBox.stateChanged.connect(self.checkBox_changed) self.accepted.connect(self.lineEdit_2.clear)
def write_settings(self): settings = QtCore.QSettings("sequana_gui", "mainapp") # tab snakemake output/logger/ipython index = self.ui.tabs_pipeline.currentIndex() settings.setValue("tab_position", index) index = self.ui.tabs_generic.currentIndex() settings.setValue("tab_generic_position", index) index = self.ui.tabs_sequana.currentIndex() settings.setValue("tab_sequana_position", index) index = self.ui.tabWidget.currentIndex() settings.setValue("tab_sequana_input_position", index)
def write_settings(self): settings = QtCore.QSettings(self._application, self._section) items = self.get_settings() for k,v in self.get_settings().items(): settings.setValue(k, v)
def read_settings(self): settings = QtCore.QSettings(self._application, self._section) for key in settings.allKeys(): value = settings.value(key) try: # This is required to skip the tab_position key/value this = getattr(self.ui, key) except: continue if isinstance(this, QW.QLineEdit): this.setText(value) elif isinstance(this, QW.QSpinBox): this.setValue(int(value)) elif isinstance(this, QW.QComboBox): index = this.findText(value) this.setCurrentIndex(index) elif isinstance(this, QW.QCheckBox): if value in ['false']: this.setChecked(False) else: this.setChecked(True) else: print('could not handle : %s' % this) # The last tab position self._tab_pos = settings.value("tab_position", 0, type=int) self.ui.tabs.setCurrentIndex(self._tab_pos)
def saveChanges(key, value): """ Save settings to registry and global store """ parent, name = key.split("/") states[parent][name] = value QSettings.setValue(key, list(value) if isinstance(value, tuple) else value)
def __init__(self, parent=None): QObject.__init__(self, parent) self.name = self.__class__.__name__ self._settings = QSettings() self._logger = logging.getLogger(self.name) self._path_name = None self._file_type = None self._file_info = None
def __init__(self, parent=None): super().__init__('settings.ini', QtCore.QSettings.IniFormat, parent)
def closeEvent(self, event: QCloseEvent): """ Called by the view when the user selects File > Quit or closes the application. :return: """ if self.maybe_save_modifications_before_continuing(): # try to save persisted state >> no need anymore, the QSettings() do it for us automatically # can_exit = self.internal_state.persist_state_to_disk( # self.get_file_path(EnvSwitcherApp.PERSISTED_STATE_FILE)) print('Terminating...') event.accept() else: event.ignore()
def writeSettings(self): settings = QtCore.QSettings("dxf2gcode", "dxf2gcode") settings.beginGroup("MainWindow") settings.setValue("size", self.size()) settings.setValue("pos", self.pos()) settings.endGroup()
def __init__(self, appname, cmd): QtWidgets.QMainWindow.__init__(self) vq_hotkeys.HotKeyMixin.__init__(self) self._vq_appname = appname self._vq_dockwidgets = [] self._vq_settings = QtCore.QSettings('invisigoth', application=appname, parent=self) self._vq_histfile = os.path.join(os.path.expanduser('~'), '.%s_history' % appname) self._dock_classes = {} self.vqInitDockWidgetClasses() self._vq_mbar = vq_menu.VQMenuBar() self.setMenuBar(self._vq_mbar) # AnimatedDocks, AllowNestedDocks, AllowTabbedDocks, ForceTabbedDocks, VerticalTabs self.setDockOptions(self.AnimatedDocks | self.AllowTabbedDocks) self._vq_cli = self.__cli_widget_class__(cmd) self._vq_cli.input.loadHistory(self._vq_histfile) self._vq_cli.sigCliQuit.connect(self.close) self.setCentralWidget(self._vq_cli) self.vqRestoreGuiSettings(self._vq_settings)
def validate(s): # the slash character is used by QSettings to denote a subgroup # we want to have a single nested structure of settings if "/" in s: return False if "\\" in s: # QSettings automatically translates '\' to '/' return False return True # provide base constructor args required by settings providers
def has_qsettings_write_permission(settings): value = datetime.datetime.now().isoformat("T") settings.setValue(MARKER_KEY, value) settings.sync() # there's a race here, if another thread/process also # performs the same check at the same time if settings.status() != QtCore.QSettings.NoError: return False if settings.value(MARKER_KEY) != value: return False settings.remove(MARKER_KEY) settings.sync() return True
def __init__(self): super(PermissionError, self).__init__("Unable to write to QSettings")
def __init__(self, plugin_name, *args, **kwargs): super(SystemIDASettings, self).__init__(plugin_name, *args, **kwargs) s = QtCore.QSettings(QtCore.QSettings.SystemScope, IDA_SETTINGS_ORGANIZATION, IDA_SETTINGS_APPLICATION) s.beginGroup(self._plugin_name) self._qsettings = QSettingsIDASettings(s)
def __init__(self, plugin_name, *args, **kwargs): super(UserIDASettings, self).__init__(plugin_name, *args, **kwargs) s = QtCore.QSettings(QtCore.QSettings.UserScope, IDA_SETTINGS_ORGANIZATION, IDA_SETTINGS_APPLICATION) s.beginGroup(self._plugin_name) self._qsettings = QSettingsIDASettings(s)
def get_system_plugin_names(): """ Get the names of all plugins at the system scope. As this is a static method, you can call the directly on IDASettings: import ida_settings print( ida_settings.IDASettings.get_system_plugin_names() ) rtype: Sequence[str] """ return QtCore.QSettings(QtCore.QSettings.SystemScope, IDA_SETTINGS_ORGANIZATION, IDA_SETTINGS_APPLICATION).childGroups()[:]
def get_user_plugin_names(): """ Get the names of all plugins at the user scope. As this is a static method, you can call the directly on IDASettings: import ida_settings print( ida_settings.IDASettings.get_user_plugin_names() ) rtype: Sequence[str] """ return QtCore.QSettings(QtCore.QSettings.UserScope, IDA_SETTINGS_ORGANIZATION, IDA_SETTINGS_APPLICATION).childGroups()[:]
def get_directory_plugin_names(config_directory=None): """ Get the names of all plugins at the directory scope. Provide a config directory path to use this method outside of IDA. As this is a static method, you can call the directly on IDASettings: import ida_settings print( ida_settings.IDASettings.get_directory_plugin_names("/tmp/ida/1/") ) type config_directory: str rtype: Sequence[str] """ ensure_ida_loaded() return QtCore.QSettings(get_directory_config_path(directory=config_directory), QtCore.QSettings.IniFormat).childGroups()[:]
def import_settings(settings, config_path): """ Import settings from the given file system path to given settings instance. type settings: IDASettingsInterface type config_path: str """ other = QtCore.QSettings(config_path, QtCore.QSettings.IniFormat) for k in other.allKeys(): settings[k] = other.value(k)
def __init__(self, modeler): QObject.__init__(self) self.modeler = modeler self._model_mgr = ModelManager(modeler) self._model_mgr.error.connect(self.error) self.settings = QSettings() self._last_model_dir = self.settings.value("last_model_dir", ".") self._copy_clipboard = None
def __init__(self, modeler): QObject.__init__(self, modeler) self.modeler = modeler self.server_mgr = ServerManager(self.modeler.ui.actionUseOpenUa) self.new_nodes = [] # the added nodes we will save self.current_path = None self.settings = QSettings() self.modified = False self.modeler.attrs_ui.attr_written.connect(self._attr_written)
def __init__(self, action): self._backend = ServerPython() self._action = action self._settings = QSettings() if OPEN62541: use_open62541 = int(self._settings.value("use_open62541_server", 0)) logger.info("Using open62541: %s", open62541) self._action.setChecked(use_open62541) self._action.toggled.connect(self._toggle_use_open62541) self._toggle_use_open62541(use_open62541) # init state else: logger.info("Open62541 python wrappers not available, disabling action") self._action.setChecked(False) self._action.setEnabled(False)
def settings(): return QSettings(qApp.organizationName(), qApp.applicationName())
def closeEvent(self, event): settings = QtCore.QSettings(_ORG, _APPNAME) cb_region = self.findChild(QtWidgets.QComboBox , "comboRegion") settings.setValue("default_region", cb_region.currentIndex())
def _browse(self): settings = QtCore.QSettings() path = settings.value('LastPath', os.getcwd()) filename, _ = QtWidgets.QFileDialog.getOpenFileName(None, 'Choose video file', path) if filename: item = QtWidgets.QListWidgetItem(os.path.basename(filename), self._list) item.setData(QtCore.Qt.UserRole, filename) settings.setValue('LastPath', os.path.dirname(filename)) self._player = Player(filename) self._player.playback_stopped.connect(self._playbackStopped)
def __init__(self): super().__init__() self.setWindowTitle('pyplaybin Qt demo') self.setCentralWidget(MainViewport(self)) settings = QtCore.QSettings() if settings.contains('Geometry'): self.restoreGeometry(settings.value('Geometry')) else: self.resize(800, 600) self.show() self.raise_()
def __init__(self, argv): super(App, self).__init__(argv) self.setOrganizationName('Metrasynth') self.setOrganizationDomain('metrasynth.warmcommunity.space') self.setApplicationName('Solar Sails') App.settings = QSettings()
def __init__(self): self.settings = QSettings('SomeGuySoftware', 'RedditDownloader') self.load_settings() self.count = 0