Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

PyQt5 QSetting doesn't save information



  • Created a programm with table and parametrs "Name" and "Points", but with QSettings, programm does not save information. Win 10, Py 3.8.2, PyQt5 5.14.2

    Programm creates Settings.ini by itself, but doesn't do anything. Help please because have no other idea how to do it

    Counter.py:

    import sys
    from random import randint
    from PyQt5 import QtWidgets, QtCore, QtGui
    
    class CustomTableView(QtWidgets.QTableView):
        def __init__(self, parent=None):
            super(CustomTableView, self).__init__(parent)
            self.setSortingEnabled(True)
    
        def KeyPressEvent(self, event: QtGui.QKeyEvent):
            if event.key() == QtCore.Qt.Key_Enter:
                print("Key_Enter ")
            elif event.key() == QtCore.Qt.Key_Return:
                print("Key_Return ")
    
    
    class NumberSortModel(QtCore.QSortFilterProxyModel):
    
        def lessThan(self, left_index: "QModelIndex",
                     right_index: "QModelIndex") -> bool:
    
            left_var: str = left_index.data(QtCore.Qt.EditRole)
            right_var: str = right_index.data(QtCore.Qt.EditRole)
    
            try:
                return float(left_var) < float(right_var)
            except (ValueError, TypeError):
                pass
    
            try:
                return left_var < right_var
            except TypeError: 
                return True
    
    
    class Counter(QtWidgets.QMainWindow):
        def __init__(self, parent=None):
            super(Counter, self).__init__(parent)
            self.setWindowFlags(QtCore.Qt.Window)
            QtWidgets.QMainWindow.__init__(self)
    
            font = QtGui.QFont("Formula1", 10, QtGui.QFont.Bold)
            self.setFont(font)
    
            central_widget = QtWidgets.QWidget()
            self.setCentralWidget(central_widget)
    
            grid_layout = QtWidgets.QGridLayout()
            central_widget.setLayout(grid_layout)
    
            self.model = QtGui.QStandardItemModel(self)
            self.model.setHorizontalHeaderLabels(["Name" , "Points"])
    
            self.proxy = NumberSortModel()
            self.proxy.setSourceModel(self.model)
    
            self.table = CustomTableView(self)
            self.table.setModel(self.proxy)
            self.table.horizontalHeader().setSectionResizeMode(QtWidgets.QHeaderView.Stretch)
    
            update_button = QtWidgets.QPushButton("Update")                           
            update_button.clicked.connect(self.on_update_button)                      
            sort_button = QtWidgets.QPushButton("Sort")
    
            self.qlineedit_name = QtWidgets.QLineEdit()
            self.qlineedit_name.resize(24, 80)
            self.qlineedit_points = QtWidgets.QLineEdit()
            self.qlineedit_points.resize(24, 80)
    
            horisontal_layout = QtWidgets.QHBoxLayout()
            horisontal_layout.addWidget(self.qlineedit_name, stretch=1)
            horisontal_layout.addWidget(self.qlineedit_points, stretch=1)
            horisontal_layout.addStretch(1)
            horisontal_layout.addWidget(update_button)                                 
            horisontal_layout.addWidget(sort_button)
            horisontal_layout.setAlignment(QtCore.Qt.AlignRight)
    
            grid_layout.addLayout(horisontal_layout, 0, 0)
            grid_layout.addWidget(self.table, 1, 0)
    
            settings = QtCore.QSettings("settings.ini", QtCore.QSettings.IniFormat)
            settings.setValue("Name", "Points")
    
        def on_update_button(self):
            name = self.qlineedit_name.text().strip()
            point = self.qlineedit_points.text().strip() if self.qlineedit_points.text().strip() else '0'
            if not point.isdigit():
                msg = QtWidgets.QMessageBox.information(self, 'ВНИМАНИЕ', 'Заполните правильно поле ввода Points!')
                return msg
    
            if not name:
                msg = QtWidgets.QMessageBox.information(self, 'ВНИМАНИЕ', 'Заполните поле ввода Name!')
                return msg
            rows  = self.table.model().rowCount()
            add_record = True
            for row in range(rows):
                if name == self.proxy.data(self.proxy.index(row, 0)):
                    #print(name)
                    add_record = False
                    row_edit = row
                    break
    
            if add_record:       
                if self.table.selectedIndexes():
                    row = self.table.selectedIndexes()[-1].row()
                    self.model.insertRow(row+1, [QtGui.QStandardItem(name), 
                                          QtGui.QStandardItem(point)])                  
    
                else:
                    self.model.appendRow([QtGui.QStandardItem(name), 
                                          QtGui.QStandardItem(point)])            
            else:                 
                self.model.setData(self.model.index(row_edit, 1), point, QtCore.Qt.EditRole)
            
            self.qlineedit_name.clear()
            self.qlineedit_points.clear()      
    
    
    if __name__ == "__main__":
        application = QtWidgets.QApplication([])
        window = Counter()
        window.setWindowTitle("Counter")
        window.setMinimumSize(480, 380)
        window.show()
        sys.exit(application.exec_())
    


  • You need to call settings.sync() to save changes to the file immediately.
    Otherwise it shall be saved when the instance is destroyed.



  • added settings.sync(), doesn't work



  • @Lcashe
    Then maybe you should print the result of settings.status() to see whether there is any error.



  • @Bonnie see literally nothing



  • @Lcashe
    Does "nothing" mean the result is 0?



  • i found out the problem. info maybe writes itself into the ini file, but with the next start information vanishes out from the file


  • Lifetime Qt Champion

    Hi,

    Set the organisation name and domain as shown in the QSettings documentation.

    Note that the code snippet seems to still be c++ but it is easy to adapt.



  • well. have no idea what the problem it is. recorded the video - https://youtu.be/60Gf27affeM @SGaist


Log in to reply