def __init__(self, organization, application, defaults=None): """ :param organization: A string name for the organization :param application: A string name for the application name :param defaults: Default configuration values for this instance in the form of nested dict instances """ # Loads the saved settings if found self.qsettings = QSettings(QSettings.IniFormat, QSettings.UserScope, organization, application) # convert the defaults into something that qsettings can handle default_settings = self._flatten_defaults(defaults) # put defaults into qsettings if they weren't there already try: self.set_qsettings_values(default_settings) # the editors/sessiontabs are pickled in config so need to remove them except ValueError: self.qsettings.remove('Editors/SessionTabs') self.set_qsettings_values(default_settings) # fixup the values of booleans - they do not evaluate correctly when read from the config file for key in self.all_keys(): try: value = self.get(key) except (KeyError, TypeError): continue if value == 'true': self.set(key, True) elif value == 'false': self.set(key, False)
def __init__(self, organization, application, defaults=None): """ :param organization: A string name for the organization :param application: A string name for the application name :param defaults: Default configuration values for this instance in the form of nested dict instances """ # Loads the saved settings if found self.qsettings = QSettings(QSettings.IniFormat, QSettings.UserScope, organization, application) # convert the defaults into something that qsettings can handle default_settings = self._flatten_defaults(defaults) # put defaults into qsettings if they weren't there already configFileKeys = self.qsettings.allKeys() for key in default_settings.keys(): if key not in configFileKeys: self.qsettings.setValue(key, default_settings[key]) # fixup the values of booleans - they do not evaluate correctly when read from the config file # TODO come up with a unit test for this for key in self.all_keys(): try: value = self.get(key) except KeyError: continue if value == 'true': self.set(key, True) elif value == 'false': self.set(key, False)
def get_setting(group, prefix, setting_name, return_type=str): """ Get a setting from the .ini file of mantid settings. NOTE: If you specify an int, but the setting contains a bool, you will get 0 for False and 1 for True, without a warning. Specifying bool will raise a TypeError if anything other than a bool or empty string is found in the settings. Not specifying a type will return a string. If nothing is found then an empty string is returned. :param group: Settings group to pull from. :param prefix: The prefix of the setting, acts like a subgroup. :param setting_name: Name of the setting. :param return_type: The type of the setting to get. :return: The chosen setting. """ settings = QSettings() settings.beginGroup(group) if return_type is bool: setting = settings.value(prefix + setting_name, type=str) if setting == "": pass elif setting == "true": setting = True elif setting == "false": setting = False else: raise TypeError("Unable to convert string into valid bool") else: setting = settings.value(prefix + setting_name, type=return_type) settings.endGroup() return setting
def __init__(self): super(DataResourceBrowser, self).__init__() vbox = QVBoxLayout() vbox.setSpacing(0) vbox.setContentsMargins(0, 0, 0, 0) self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Expanding) self.setMinimumSize(QSize(250, 400)) # cache pre-load index (otherwise it gets overwritten during init index = int(QSettings().value('databrowsertab', 0)) self.browsertabwidget = BrowserTabWidget(self) self.browsertabbar = BrowserTabBar(self.browsertabwidget) self.browsertabbar.sigAddBrowser.connect(self.addBrowser) self.browsertabbar.tabCloseRequested.connect(self.closetab) # Add the required 'Local' browser self.addBrowser(DataBrowser(LocalFileSystemTree()), "Local", closable=False) self.addBrowser(DatabrokerCatalogPlugin().controller, "Databroker", closable=False) self.browsertabbar.setCurrentIndex(index) vbox.addWidget(self.browsertabwidget) self.setLayout(vbox)
def read_settings(): """Read application settings. Returns ------- settings : dict The restored settings values are returned in a dictionary for further processing. """ settings = QSettings() recent = settings.value("recent") if not recent: recent = [] # default is empty list toolbar = settings.value("toolbar") if toolbar is None: # default is True toolbar = True statusbar = settings.value("statusbar") if statusbar is None: # default is True statusbar = True geometry = settings.value("geometry") state = settings.value("state") return { "recent": recent, "statusbar": statusbar, "geometry": geometry, "state": state, "toolbar": toolbar }
def __init__(self): super(MainWindowBase, self).__init__() # Environment path self.env = "" # Alignment mode self.alignment_mode = 0 # Entities list self.vpoint_list = [] self.vlink_list = [VLink(VLink.FRAME, 'White', (), color_rgb)] # Condition list of context menus self.context = _Context() # Preference self.prefer = Preferences() # Set path from command line home_dir = QDir.home() self.settings = QSettings(home_dir.absoluteFilePath(".pyslvs.ini"), QSettings.IniFormat, self) if ARGUMENTS.c: self.set_locate(QDir(ARGUMENTS.c).absolutePath()) else: home_dir.cd("Desktop") env = self.settings.value("ENV", home_dir.absolutePath()) self.set_locate(str(env)) # Initialize custom UI self.__undo_redo() self.__appearance() self.__alignment() self.__free_move() self.__options() self.__context_menu()
def __init__(self, log=None): super().__init__() if log: self.log = log.getChild('Conf') self.log.setLevel(30) else: self.log = logging.getLogger() self.log.setLevel(99) self.log.debug('Initializing') self.qsettings = QSettings() self.qsettings.setIniCodec('UTF-8') self.options = None self.option_spec = self.load_option_spec() self.options = self.load_options() self.full_name = "{} {}".format(QCoreApplication.applicationName(), QCoreApplication.applicationVersion()) # options that need fast access are also defined as attributes, which # are updated by calling update_attributes() # (on paper it's 4 times faster, but I don't think it matters in my case) self.logger_table_font = None self.logger_table_font_size = None self.logger_row_height = None self.benchmark_interval = None self.update_attributes()
def load_default_file(line_edit_field, q_settings_group_key, q_settings_key): settings = QSettings() settings.beginGroup(q_settings_group_key) default_file = settings.value(q_settings_key, "", type=str) settings.endGroup() line_edit_field.setText(default_file)
def __init__(self): super(LocalFileSystemResourcePlugin, self).__init__() self.uri = parse.urlparse(QSettings().value( "lastlocaldir", os.getcwd())) self.setResolveSymlinks(True) self.setRootPath(parse.urlunparse(self.uri))
def load_property(q_settings_group_key, q_settings_key, type=str): settings = QSettings() settings.beginGroup(q_settings_group_key) default = False if type == bool else "" default_property = settings.value(q_settings_key, default, type=type) settings.endGroup() return default_property
def test_set_setting_with_string(self): set_setting(GROUP, PREFIX, "something", "value") settings = QSettings() settings.beginGroup(GROUP) returned = settings.value(PREFIX + "something") settings.endGroup() self.assertEqual(returned, "value")
def test_set_setting_with_int(self): set_setting(GROUP, PREFIX, "something", 10) settings = QSettings() settings.beginGroup(GROUP) returned = settings.value(PREFIX + "something", type=int) settings.endGroup() self.assertEqual(returned, 10)
def restore_perspectives(self): ''' Restore the perspective listo of the dock manager ''' settings = QSettings("Settings.ini", QSettings.IniFormat) self.dock_manager.load_perspectives(settings) self.perspective_combo_box.clear() self.perspective_combo_box.addItems(self.dock_manager.perspective_names())
def accept(self): intersection = set(self.get_metadata().keys()).intersection(self.reserved) if intersection: msg.notifyMessage(f'The field name "{list(intersection)[0]}" is reserved and cannot be used.') else: super(MetadataDialog, self).accept() QSettings().setValue(self._qsettings_key, self.parameter.saveState())
def _read_settings(self): self.logger.info("MainWindow._read_settings") settings = QSettings(ORGANIZATION_NAME, APPLICATION_NAME) pos = settings.value("pos", QPoint(200, 200)) size = settings.value("size", QSize(400, 400)) self.resize(size) self.move(pos)
def __fetchSettings(self): settings = QSettings("Equinor", "Ert-Gui") geo = settings.value("geometry") if geo: self.restoreGeometry(geo) wnd = settings.value("windowState") if wnd: self.restoreState(wnd)
def test_get_setting_with_bool_true(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", True) settings.endGroup() self.assertEqual( get_setting(GROUP, PREFIX, "something", return_type=bool), True)
def test_get_setting_bool_specifying_int(self): settings = QSettings() settings.beginGroup(GROUP) settings.setValue(PREFIX + "something", True) settings.endGroup() self.assertEqual( get_setting(GROUP, PREFIX, "something", return_type=int), 1)
def test_set_setting_with_bool_true(self): set_setting(GROUP, PREFIX, "something", True) settings = QSettings() settings.beginGroup("CustomInterfaces") returned = settings.value("EngineeringDiffraction2/" + "something", type=bool) settings.endGroup() self.assertEqual(returned, True)
def save_state(self): ''' Saves the dock manager state and the main window geometry ''' settings = QSettings("Settings.ini", QSettings.IniFormat) settings.setValue("mainWindow/Geometry", self.saveGeometry()) settings.setValue("mainWindow/State", self.saveState()) settings.setValue("mainWindow/DockingState", self.dock_manager.save_state())
def __init__(self, parent, app_settings): super().__init__(parent) self._log = logging.getLogger(__name__) self._settings = QSettings() self._app_settings = app_settings self._load_ui() # Flag indicating whether the user has requested the GUI settings to be reset. # If so, the caller should disable any further settings recording logic self.cleared = False
def __setitem__(self, key, value): groupings = self._get_groups(key) key = groupings.pop() settings = QSettings(parent=self.parent) for g in groupings: settings.beginGroup(g) settings.setValue(key, value) for g in groupings: settings.endGroup()
def restore(self): try: self.fromState(pickle.loads(QSettings().value(self.name()))) except (AttributeError, TypeError, SystemError, KeyError, ModuleNotFoundError) as ex: # No settings saved msg.logError(ex) msg.logMessage( f"Could not restore settings for {self.name} plugin; re-initializing settings...", level=msg.WARNING )
def clear_defaults(): """ Clear all settings in defaults group. Should only be run once during application start, as it will undo any defaults that have been set. """ settings = QSettings() settings.beginGroup('defaults') settings.remove("") settings.endGroup()
def init(cls, parent=None): ''' 初始化配置实例 :param cls: :param parent: ''' if not cls.instance: cls.instance = QSettings(__config_path__, QSettings.IniFormat, parent) cls.instance.setIniCodec(QTextCodec.codecForName('utf-8'))
def save_on_closing(self): # make sure the Last Version is updated on closing settings = QSettings() settings.beginGroup(self.DO_NOT_SHOW_GROUP) settings.setValue(self.LAST_VERSION, release_notes_url()) settings.endGroup() self.store_facility(self.view.cb_facility.currentText()) self.action_instrument_changed(self.view.cb_instrument.currentText()) ConfigService.saveConfig(ConfigService.getUserFilename()) self.parent.config_updated()
def make_app(): app = QApplication(sys.argv) if getattr(sys, 'frozen', False): icon_path = os.path.join(sys._MEIPASS, 'Icon.ico') else: icon_path = os.path.abspath( os.path.join(os.path.dirname('__file__'), '../icons/Icon.ico')) if os.path.exists(icon_path): app.setWindowIcon(QIcon(icon_path)) return app, Preferences(QSettings("3ll3d00d", "qvibe-analyser"))
def action_close(self): # make sure the Last Version is updated on closing settings = QSettings() settings.beginGroup(self.DO_NOT_SHOW_GROUP) settings.setValue(self.LAST_VERSION, release_notes_url()) settings.endGroup() ConfigService.saveConfig(ConfigService.getUserFilename()) self.parent.config_updated() self.view.close()
def __init__(self, settings=None): """ Initialization. @param settings: QSettings object passed by the main application """ super(GeneralSettings, self).__init__() if settings is not None: self._settings = settings else: self._settings = QSettings()
def restoreSettings(self, s=None): if s is None: s = QSettings() guess = self.parameterTable.guess() s.beginGroup('HangingModel') for key in guess: guess[key] = s.value(key, type=float) s.endGroup() #print('Restoring settings:', guess) self.parameterTable.setGuess(guess)