Skip to content

[PyQt5] Use "QSettings" to store user's settings

When we using PyQt5 to develop a Python GUI, sometimes we have a request to store the user's settings, such as user customize the interface appearance color. If we don't save this color setting, the next time the user opens the program, the appearance color is still default.

Of course we can save this setting in another file, but I think, using the QSettings built-in PyQt5 is another good choice.

If you want to know more about PyQt5, you can read their PyPI: https://pypi.org/project/PyQt5/

If you want to read some tutorial of PyQt5, maybe you can refer my article: [PyQt5] Tutorial(1) Install PyQt5 and print "Hello World!"


How to use QSettings?

The method of using QSettings is so easy, we just need to initialize this object, and use setValue() method to save setting, use value() to get setting.

# -*- coding: utf-8 -*-
import sys
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *


class MainWindow(QWidget):
    def __init__(self):
        super(MainWindow, self).__init__()
        self.resize(200, 100)

        self.settings = QSettings()

        self.label_display = QLabel(self)
        self.label_display.setGeometry(0, 0, 100, 10)

        try: self.label_display.setText(self.settings.value('context'))
        except: self.label_display.setText('TEST')

        self.editLine = QLineEdit(self)
        self.editLine.setGeometry(0, 20, 100, 20)

        self.button = QPushButton(self)
        self.button.clicked.connect(self.buttonEvent)
        self.button.setGeometry(0, 40, 100, 20)
        self.button.setText('Enter')

    def buttonEvent(self):
        self.settings.setValue('context', self.editLine.text())
        self.label_display.setText(self.settings.value('context'))


if __name__ == '__main__':
    app = QApplication([])
    window = MainWindow()
    window.show()
    sys.exit(app.exec_())



Output:


I key in the number 9999 right now.


We can see 9999 is show on our interface. And we close the window and restart.

As you can see, the number show on the screen is still 9999.

Leave a Reply