Search code examples
pythonpyside2qsettings

How to save/change text of 'QLineEdit' in 'QSettings' and get on 'QPushButton's' call


I want to save/change my 'QLineEdit' text in my app and get again by using 'QPushButton' on some specific position.


Solution

  • The logic is to associate the information with a key, in the following example I show how the text is saved when the text is modified and then the text is retrieved by pressing the button.

    from PySide2 import QtCore, QtWidgets
    
    
    class Widget(QtWidgets.QWidget):
        def __init__(self, parent=None):
            super().__init__(parent)
    
            self.m_le = QtWidgets.QLineEdit()
            self.m_le.textChanged.connect(self.onTextChanged)
            self.m_button = QtWidgets.QPushButton("Press Me")
            self.m_button.clicked.connect(self.onClicked)
    
            lay = QtWidgets.QVBoxLayout(self)
            lay.addWidget(self.m_le)
            lay.addWidget(self.m_button)
    
        @QtCore.Slot(str)
        def onTextChanged(self, text):
            settings = QtCore.QSettings()
            settings.setValue("text", text)
    
        @QtCore.Slot()
        def onClicked(self):
            settings = QtCore.QSettings()
            text = settings.value("text")
            print(text)
    
    
    if __name__ == "__main__":
        import sys
    
        app = QtWidgets.QApplication(sys.argv)
        w = Widget()
        w.show()
        sys.exit(app.exec_())