当前位置: 首页>>代码示例>>Python>>正文


Python QtCore.QSettings类代码示例

本文整理汇总了Python中AnyQt.QtCore.QSettings的典型用法代码示例。如果您正苦于以下问题:Python QSettings类的具体用法?Python QSettings怎么用?Python QSettings使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


在下文中一共展示了QSettings类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: show_survey

def show_survey():
    # If run for the first time, open a browser tab with a survey
    settings = QSettings()
    show_survey = settings.value("startup/show-survey", True, type=bool)
    if show_survey:
        question = QMessageBox(
            QMessageBox.Question,
            'Orange Survey',
            'We would like to know more about how our software is used.\n\n'
            'Would you care to fill our short 1-minute survey?',
            QMessageBox.Yes | QMessageBox.No)
        question.setDefaultButton(QMessageBox.Yes)
        later = question.addButton('Ask again later', QMessageBox.NoRole)
        question.setEscapeButton(later)

        def handle_response(result):
            if result == QMessageBox.Yes:
                success = QDesktopServices.openUrl(
                    QUrl("https://orange.biolab.si/survey/short.html"))
                settings.setValue("startup/show-survey", not success)
            else:
                settings.setValue("startup/show-survey", result != QMessageBox.No)

        question.finished.connect(handle_response)
        question.show()
        return question
开发者ID:astaric,项目名称:orange3,代码行数:26,代码来源:__main__.py

示例2: __quicktipOnce

    def __quicktipOnce(self):
        filename = os.path.join(settings.widget_settings_dir(),
                                "user-session-state.ini")
        namespace = ("user-message-history/{0.__module__}.{0.__qualname__}"
                     .format(type(self)))
        session_hist = QSettings(filename, QSettings.IniFormat)
        session_hist.beginGroup(namespace)
        messages = self.UserAdviceMessages

        def _ispending(msg):
            return not session_hist.value(
                "{}/confirmed".format(msg.persistent_id),
                defaultValue=False, type=bool)
        messages = [msg for msg in messages if _ispending(msg)]

        if not messages:
            return

        message = messages[self.__msgchoice % len(messages)]
        self.__msgchoice += 1

        self.__showMessage(message)

        def _userconfirmed():
            session_hist = QSettings(filename, QSettings.IniFormat)
            session_hist.beginGroup(namespace)
            session_hist.setValue(
                "{}/confirmed".format(message.persistent_id), True)
            session_hist.sync()

        self.__msgwidget.accepted.connect(_userconfirmed)
开发者ID:cheral,项目名称:orange3,代码行数:31,代码来源:widget.py

示例3: init

    def init(self):
        """
        Initialize the QCoreApplication.organizationDomain, applicationName,
        applicationVersion and the default settings format.

        Should only be run once at application startup.
        """
        QCoreApplication.setOrganizationDomain(self.OrganizationDomain)
        QCoreApplication.setApplicationName(self.ApplicationName)
        QCoreApplication.setApplicationVersion(self.ApplicationVersion)
        QSettings.setDefaultFormat(QSettings.IniFormat)
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:11,代码来源:config.py

示例4: save_plot

def save_plot(data, file_formats, filename=""):
    _LAST_DIR_KEY = "directories/last_graph_directory"
    _LAST_FILTER_KEY = "directories/last_graph_filter"
    settings = QSettings()
    start_dir = settings.value(_LAST_DIR_KEY, filename)
    if not start_dir or \
            (not os.path.exists(start_dir) and
             not os.path.exists(os.path.split(start_dir)[0])):
        start_dir = os.path.expanduser("~")
    last_filter = settings.value(_LAST_FILTER_KEY, "")
    filename, writer, filter = \
        filedialogs.open_filename_dialog_save(start_dir, last_filter, file_formats)
    if not filename:
        return
    try:
        writer.write(filename, data)
    except OSError as e:
        mb = QMessageBox(
            None,
            windowTitle="Error",
            text='Error occurred while saving file "{}": {}'.format(filename, e),
            detailedText=traceback.format_exc(),
            icon=QMessageBox.Critical)
        mb.exec_()
    else:
        settings.setValue(_LAST_DIR_KEY, os.path.split(filename)[0])
        settings.setValue(_LAST_FILTER_KEY, filter)
开发者ID:PrimozGodec,项目名称:orange3,代码行数:27,代码来源:saveplot.py

示例5: TestQSettings_array

class TestQSettings_array(unittest.TestCase):
    filename = ""  # type: str

    def setUp(self):
        self.file = tempfile.NamedTemporaryFile()
        self.filename = self.file.name
        self.settings = QSettings(self.filename, QSettings.IniFormat)

    def tearDown(self):
        self.settings.sync()
        del self.settings
        self.file.close()

    def test_readwrite_array(self):
        s = self.settings
        scheme = {
            "name": str,
            "price": int
        }
        items = QSettings_readArray(s, "items", scheme)
        self.assertSequenceEqual(items, [])
        items_ = [
            {"name": "apple", "price": 10},
            {"name": "pear", "price": 12},
        ]
        QSettings_writeArray(s, "items", items_)
        items = QSettings_readArray(s, "items", scheme)
        self.assertSequenceEqual(items, items_)
        scheme = {
            "quality": (int, -1),
            **scheme
        }
        items = QSettings_readArray(s, "items", scheme)
        self.assertSequenceEqual(items, [{"quality": -1, **d} for d in items_])

        QSettings_writeArrayItem(
            s, "items", 1, {"name": "banana", "price": 5, "quality": 5},
            arraysize=2
        )
        items = QSettings_readArray(s, "items", scheme)
        self.assertSequenceEqual(items, [
            {"name": "apple", "price": 10, "quality": -1},
            {"name": "banana", "price": 5, "quality": 5}
        ])
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:44,代码来源:test_settings.py

示例6: test_qsettings_type

    def test_qsettings_type(self):
        """
        Test if QSettings as exported by qtcompat has the 'type' parameter.
        """
        with tempfile.NamedTemporaryFile("w+b", suffix=".ini",
                                         delete=False) as f:
            settings = QSettings(f.name, QSettings.IniFormat)
            settings.setValue("bar", "foo")

            self.assertEqual(settings.value("bar", type=str), "foo")
            settings.setValue("frob", 4)

            del settings
            settings = QSettings(f.name, QSettings.IniFormat)
            self.assertEqual(settings.value("bar", type=str), "foo")
            self.assertEqual(settings.value("frob", type=int), 4)
开发者ID:PrimozGodec,项目名称:orange3,代码行数:16,代码来源:test_settings.py

示例7: init

def init():
    """
    Initialize the QCoreApplication.organizationDomain, applicationName,
    applicationVersion and the default settings format. Will only run once.

    .. note:: This should not be run before QApplication has been initialized.
              Otherwise it can break Qt's plugin search paths.

    """
    dist = pkg_resources.get_distribution("Orange3")
    version = dist.version
    # Use only major.minor
    version = ".".join(version.split(".", 2)[:2])

    QCoreApplication.setOrganizationDomain("biolab.si")
    QCoreApplication.setApplicationName("Orange Canvas")
    QCoreApplication.setApplicationVersion(version)
    QSettings.setDefaultFormat(QSettings.IniFormat)

    # Make it a null op.
    global init
    init = lambda: None
开发者ID:randxie,项目名称:orange3,代码行数:22,代码来源:config.py

示例8: fix_set_proxy_env

def fix_set_proxy_env():
    """
    Set http_proxy/https_proxy environment variables (for requests, pip, ...)
    from user-specified settings or, if none, from system settings on OS X
    and from registry on Windos.
    """
    # save default proxies so that setting can be reset
    global default_proxies
    if default_proxies is None:
        default_proxies = getproxies()  # can also read windows and macos settings

    settings = QSettings()
    proxies = getproxies()
    for scheme in set(["http", "https"]) | set(proxies):
        from_settings = settings.value("network/" + scheme + "-proxy", "", type=str)
        from_default = default_proxies.get(scheme, "")
        env_scheme = scheme + '_proxy'
        if from_settings:
            os.environ[env_scheme] = from_settings
        elif from_default:
            os.environ[env_scheme] = from_default  # crucial for windows/macos support
        else:
            os.environ.pop(env_scheme, "")
开发者ID:astaric,项目名称:orange3,代码行数:23,代码来源:__main__.py

示例9: save_plot

def save_plot(data, file_formats, filename=""):
    _LAST_DIR_KEY = "directories/last_graph_directory"
    _LAST_FILTER_KEY = "directories/last_graph_filter"
    settings = QSettings()
    start_dir = settings.value(_LAST_DIR_KEY, filename)
    if not start_dir or \
            (not os.path.exists(start_dir) and
             not os.path.exists(os.path.split(start_dir)[0])):
        start_dir = os.path.expanduser("~")
    last_filter = settings.value(_LAST_FILTER_KEY, "")
    filename, writer, filter = \
        filedialogs.get_file_name(start_dir, last_filter, file_formats)
    if not filename:
        return
    try:
        writer.write(filename, data)
    except Exception as e:
        QMessageBox.critical(
            None, "Error", 'Error occurred while saving file "{}": {}'.format(filename, e))
    else:
        settings.setValue(_LAST_DIR_KEY, os.path.split(filename)[0])
        settings.setValue(_LAST_FILTER_KEY, filter)
开发者ID:RachitKansal,项目名称:orange3,代码行数:22,代码来源:saveplot.py

示例10: __init__

    def __init__(self, data):
        icon = QApplication.style().standardIcon(QStyle.SP_MessageBoxWarning)
        F = self.DataField

        def _finished(*, key=(data.get(F.MODULE),
                              data.get(F.WIDGET_MODULE)),
                      filename=data.get(F.WIDGET_SCHEME)):
            self._cache.add(key)
            try:
                os.remove(filename)
            except Exception:
                pass

        super().__init__(None, Qt.Window, modal=True,
                         sizeGripEnabled=True, windowIcon=icon,
                         windowTitle='Unexpected Error',
                         finished=_finished)
        self._data = data

        layout = QVBoxLayout(self)
        self.setLayout(layout)
        labels = QWidget(self)
        labels_layout = QHBoxLayout(self)
        labels.setLayout(labels_layout)
        labels_layout.addWidget(QLabel(pixmap=icon.pixmap(50, 50)))
        labels_layout.addWidget(QLabel(
            'The program encountered an unexpected error. Please<br>'
            'report it anonymously to the developers.<br><br>'
            'The following data will be reported:'))
        labels_layout.addStretch(1)
        layout.addWidget(labels)
        font = QFont('Monospace', 10)
        font.setStyleHint(QFont.Monospace)
        font.setFixedPitch(True)
        textbrowser = QTextBrowser(self,
                                   font=font,
                                   openLinks=False,
                                   lineWrapMode=QTextBrowser.NoWrap,
                                   anchorClicked=QDesktopServices.openUrl)
        layout.addWidget(textbrowser)

        def _reload_text():
            add_scheme = cb.isChecked()
            settings.setValue('error-reporting/add-scheme', add_scheme)
            lines = ['<table>']
            for k, v in data.items():
                if k.startswith('_'):
                    continue
                _v, v = v, escape(str(v))
                if k == F.WIDGET_SCHEME:
                    if not add_scheme:
                        continue
                    v = '<a href="{}">{}</a>'.format(urljoin('file:', pathname2url(_v)), v)
                if k in (F.STACK_TRACE, F.LOCALS):
                    v = v.replace('\n', '<br>').replace(' ', '&nbsp;')
                lines.append('<tr><th align="left">{}:</th><td>{}</td></tr>'.format(k, v))
            lines.append('</table>')
            textbrowser.setHtml(''.join(lines))

        settings = QSettings()
        cb = QCheckBox(
            'Include workflow (data will NOT be transmitted)', self,
            checked=settings.value('error-reporting/add-scheme', True, type=bool))
        cb.stateChanged.connect(_reload_text)
        _reload_text()

        layout.addWidget(cb)
        buttons = QWidget(self)
        buttons_layout = QHBoxLayout(self)
        buttons.setLayout(buttons_layout)
        buttons_layout.addWidget(
            QPushButton('Send Report (Thanks!)', default=True, clicked=self.accept))
        buttons_layout.addWidget(QPushButton("Don't Send", default=False, clicked=self.reject))
        layout.addWidget(buttons)
开发者ID:PrimozGodec,项目名称:orange3,代码行数:74,代码来源:errorreporting.py

示例11: _userconfirmed

 def _userconfirmed():
     session_hist = QSettings(filename, QSettings.IniFormat)
     session_hist.beginGroup(namespace)
     session_hist.setValue(
         "{}/confirmed".format(message.persistent_id), True)
     session_hist.sync()
开发者ID:cheral,项目名称:orange3,代码行数:6,代码来源:widget.py

示例12: main


#.........这里部分代码省略.........
    if options.clear_widget_settings or \
            os.path.isfile(clear_settings_flag):
        log.info("Clearing widget settings")
        shutil.rmtree(
            config.widget_settings_dir(),
            ignore_errors=True)

    # Set http_proxy environment variables, after (potentially) clearing settings
    fix_set_proxy_env()

    file_handler = logging.FileHandler(
        filename=os.path.join(config.log_dir(), "canvas.log"),
        mode="w"
    )

    file_handler.setLevel(root_level)
    rootlogger.addHandler(file_handler)

    # intercept any QFileOpenEvent requests until the main window is
    # fully initialized.
    # NOTE: The QApplication must have the executable ($0) and filename
    # arguments passed in argv otherwise the FileOpen events are
    # triggered for them (this is done by Cocoa, but QApplicaiton filters
    # them out if passed in argv)

    open_requests = []

    def onrequest(url):
        log.info("Received an file open request %s", url)
        open_requests.append(url)

    app.fileOpenRequest.connect(onrequest)

    settings = QSettings()

    stylesheet = options.stylesheet or defaultstylesheet
    stylesheet_string = None

    if stylesheet != "none":
        if os.path.isfile(stylesheet):
            with open(stylesheet, "r") as f:
                stylesheet_string = f.read()
        else:
            if not os.path.splitext(stylesheet)[1]:
                # no extension
                stylesheet = os.path.extsep.join([stylesheet, "qss"])

            pkg_name = canvas.__name__
            resource = "styles/" + stylesheet

            if pkg_resources.resource_exists(pkg_name, resource):
                stylesheet_string = \
                    pkg_resources.resource_string(pkg_name, resource).decode()

                base = pkg_resources.resource_filename(pkg_name, "styles")

                pattern = re.compile(
                    r"^\[email protected]([a-zA-Z0-9_]+?)\s*:\s*([a-zA-Z0-9_/]+?);\s*$",
                    flags=re.MULTILINE
                )

                matches = pattern.findall(stylesheet_string)

                for prefix, search_path in matches:
                    QDir.addSearchPath(prefix, os.path.join(base, search_path))
                    log.info("Adding search path %r for prefix, %r",
开发者ID:astaric,项目名称:orange3,代码行数:67,代码来源:__main__.py

示例13: check_for_updates

def check_for_updates():
    settings = QSettings()
    check_updates = settings.value('startup/check-updates', True, type=bool)
    last_check_time = settings.value('startup/last-update-check-time', 0, type=int)
    ONE_DAY = 86400

    if check_updates and time.time() - last_check_time > ONE_DAY:
        settings.setValue('startup/last-update-check-time', int(time.time()))

        from Orange.version import version as current

        class GetLatestVersion(QThread):
            resultReady = pyqtSignal(str)

            def run(self):
                try:
                    request = Request('https://orange.biolab.si/version/',
                                      headers={
                                          'Accept': 'text/plain',
                                          'Accept-Encoding': 'gzip, deflate',
                                          'Connection': 'close',
                                          'User-Agent': self.ua_string()})
                    contents = urlopen(request, timeout=10).read().decode()
                # Nothing that this fails with should make Orange crash
                except Exception:  # pylint: disable=broad-except
                    log.exception('Failed to check for updates')
                else:
                    self.resultReady.emit(contents)

            @staticmethod
            def ua_string():
                is_anaconda = 'Continuum' in sys.version or 'conda' in sys.version
                return 'Orange{orange_version}:Python{py_version}:{platform}:{conda}'.format(
                    orange_version=current,
                    py_version='.'.join(sys.version[:3]),
                    platform=sys.platform,
                    conda='Anaconda' if is_anaconda else '',
                )

        def compare_versions(latest):
            version = pkg_resources.parse_version
            if version(latest) <= version(current):
                return
            question = QMessageBox(
                QMessageBox.Information,
                'Orange Update Available',
                'A newer version of Orange is available.<br><br>'
                '<b>Current version:</b> {}<br>'
                '<b>Latest version:</b> {}'.format(current, latest),
                textFormat=Qt.RichText)
            ok = question.addButton('Download Now', question.AcceptRole)
            question.setDefaultButton(ok)
            question.addButton('Remind Later', question.RejectRole)
            question.finished.connect(
                lambda:
                question.clickedButton() == ok and
                QDesktopServices.openUrl(QUrl("https://orange.biolab.si/download/")))
            question.show()

        thread = GetLatestVersion()
        thread.resultReady.connect(compare_versions)
        thread.start()
        return thread
开发者ID:astaric,项目名称:orange3,代码行数:63,代码来源:__main__.py

示例14: test_settings

    def test_settings(self):
        spec = [config_slot("foo", bool, True, "foo doc"),
                config_slot("bar", int, 0, "bar doc"),
                ]

        store = QSettings(QSettings.IniFormat, QSettings.UserScope,
                          "biolab.si", "Orange Canvas Unit Tests")
        store.clear()
        settings = Settings(defaults=spec, store=store)

        self.assertEqual(settings["foo"], True)
        self.assertEqual(settings.get("foo"), True)

        self.assertEqual(settings.get("bar", 3), 0, "Defaults")
        self.assertEqual(settings.get("bar"), settings["bar"])

        self.assertEqual(settings.get("does not exist", "^&"), "^&",
                         "get with default")

        self.assertIs(settings.get("does not exist"), None)

        with self.assertRaises(KeyError):
            settings["does not exist"]

        self.assertTrue(settings.isdefault("foo"))

        changed = []

        settings.valueChanged.connect(
            lambda key, value: changed.append((key, value))
        )

        settings["foo"] = False
        self.assertEqual(changed[-1], ("foo", False), "valueChanged signal")
        self.assertEqual(len(changed), 1)
        self.assertEqual(settings["foo"], False, "updated value")
        self.assertEqual(settings.get("foo"), False)
        self.assertFalse(settings.isdefault("foo"))

        settings["bar"] = 1
        self.assertEqual(changed[-1], ("bar", 1), "valueChanged signal")
        self.assertEqual(len(changed), 2)
        self.assertEqual(settings["bar"], 1)
        self.assertFalse(settings.isdefault("bar"))

        del settings["bar"]
        self.assertEqual(settings["bar"], 0)
        self.assertEqual(changed[-1], ("bar", 0))

        # Only str or unicode can be keys
        with self.assertRaises(TypeError):
            settings[1] = 3

        # value type check
        with self.assertRaises(TypeError):
            settings["foo"] = []

        self.assertEqual(len(changed), 3)

        settings.add_default_slot(config_slot("foobar/foo", object, None, ""))

        group = settings.group("foobar")

        self.assertIs(group["foo"], None)
        group["foo"] = 3

        self.assertEqual(changed[-1], ("foobar/foo", 3))

        group["foonew"] = 5
        self.assertIn("foobar/foonew", settings)

        settings["newkey"] = "newkeyvalue"
        self.assertIn("newkey", settings)

        group1 = group.group("bar")
        group1["barval"] = "barval"

        self.assertIn("foobar/bar/barval", settings)

        settings["foobar/bar/barval"] = 5
        self.assertEqual(changed[-1], ("foobar/bar/barval", 5))

        settings.clear()
        self.assertSetEqual(set(settings.keys()),
                            set(["foo", "bar", "foobar/foo"]))
开发者ID:PrimozGodec,项目名称:orange3,代码行数:85,代码来源:test_settings.py

示例15: setUp

 def setUp(self):
     self.file = tempfile.NamedTemporaryFile()
     self.filename = self.file.name
     self.settings = QSettings(self.filename, QSettings.IniFormat)
开发者ID:ales-erjavec,项目名称:orange-canvas,代码行数:4,代码来源:test_settings.py


注:本文中的AnyQt.QtCore.QSettings类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。