Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. General and Desktop
  4. PyQt5 QSetting doesn't save information
Forum Updated to NodeBB v4.3 + New Features

PyQt5 QSetting doesn't save information

Scheduled Pinned Locked Moved Unsolved General and Desktop
9 Posts 3 Posters 962 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • L Offline
    L Offline
    Lcashe
    wrote on last edited by
    #1

    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_())
    
    1 Reply Last reply
    0
    • B Offline
      B Offline
      Bonnie
      wrote on last edited by Bonnie
      #2

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

      1 Reply Last reply
      0
      • L Offline
        L Offline
        Lcashe
        wrote on last edited by
        #3

        added settings.sync(), doesn't work

        B 1 Reply Last reply
        0
        • L Lcashe

          added settings.sync(), doesn't work

          B Offline
          B Offline
          Bonnie
          wrote on last edited by Bonnie
          #4

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

          1 Reply Last reply
          0
          • L Offline
            L Offline
            Lcashe
            wrote on last edited by
            #5

            @Bonnie see literally nothing

            B 1 Reply Last reply
            0
            • L Lcashe

              @Bonnie see literally nothing

              B Offline
              B Offline
              Bonnie
              wrote on last edited by
              #6

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

              1 Reply Last reply
              0
              • L Offline
                L Offline
                Lcashe
                wrote on last edited by
                #7

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

                1 Reply Last reply
                0
                • SGaistS Offline
                  SGaistS Offline
                  SGaist
                  Lifetime Qt Champion
                  wrote on last edited by
                  #8

                  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.

                  Interested in AI ? www.idiap.ch
                  Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

                  1 Reply Last reply
                  1
                  • L Offline
                    L Offline
                    Lcashe
                    wrote on last edited by Lcashe
                    #9

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

                    1 Reply Last reply
                    0

                    • Login

                    • Login or register to search.
                    • First post
                      Last post
                    0
                    • Categories
                    • Recent
                    • Tags
                    • Popular
                    • Users
                    • Groups
                    • Search
                    • Get Qt Extensions
                    • Unsolved