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. How to implement def settings_read() and def settings_write() QSettings with QTableView
QtWS25 Last Chance

How to implement def settings_read() and def settings_write() QSettings with QTableView

Scheduled Pinned Locked Moved Unsolved General and Desktop
11 Posts 3 Posters 494 Views
  • 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 Lcashe
    #1

    I'm here again as I'm that stupid to understand how to solve the problem.
    How to implement this thing into my code?

    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)
    
            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.setAlignment(QtCore.Qt.AlignRight)
    
            grid_layout.addLayout(horisontal_layout, 0, 0)
            grid_layout.addWidget(self.table, 1, 0)
    
    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_())s
    
    1 Reply Last reply
    0
    • SGaistS Offline
      SGaistS Offline
      SGaist
      Lifetime Qt Champion
      wrote on last edited by
      #2

      Hi,

      How to implement what ?

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

      L 1 Reply Last reply
      0
      • SGaistS SGaist

        Hi,

        How to implement what ?

        L Offline
        L Offline
        Lcashe
        wrote on last edited by
        #3

        @SGaist yup, sorry, corrected

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

          But what do you want to achieve with QSettings and QTableView ?

          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
          0
          • L Offline
            L Offline
            Lcashe
            wrote on last edited by
            #5

            I don't know how to do it. hoping ong QSettings just because don't know another way

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

              Let me rephrase that: what is it that you want to do with QSettings in relation with QTableView ? What do you want to store in QSettings ? What do you want to load from it ?

              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
              0
              • L Offline
                L Offline
                Lcashe
                wrote on last edited by
                #7

                well. maybe can't explain clearly. i have table. i input info with qlineedit in this table. i want when i open the programm next time, the information not to vanish out, other word - to save info

                JonBJ 1 Reply Last reply
                0
                • L Lcashe

                  well. maybe can't explain clearly. i have table. i input info with qlineedit in this table. i want when i open the programm next time, the information not to vanish out, other word - to save info

                  JonBJ Offline
                  JonBJ Offline
                  JonB
                  wrote on last edited by
                  #8

                  @Lcashe
                  Let's just be clear about what you want. Forget about the implementation details like QSettings for a moment.

                  Do you persist (save) the model data? When you reload the model, the view will re-show the details of whatever record(s) it is bound to. Normally that is all one does.

                  The only point of persisting the values in the view is if you allow the user to type in some stuff, but then not commit it to the model and quit the application. And then when he re-runs the application you wish to pick up what he had typed into the widgets but not saved to the model. Is that what you want to achieve?

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

                    @JonB said in How to implement def settings_read() and def settings_write() QSettings with QTableView:

                    The only point of persisting the values in the view is if you allow the user to type in some stuff, but then not commit it to the model and quit the application. And then when he re-runs the application you wish to pick up what he had typed into the widgets but not saved to the model. Is that what you want to achieve?

                    Not exactly. I want to open the programm, write name and points, than see it in the table and save it, and when i start the programm next time, see this information (name, points) again, instead of clear table

                    JonBJ 1 Reply Last reply
                    0
                    • L Lcashe

                      @JonB said in How to implement def settings_read() and def settings_write() QSettings with QTableView:

                      The only point of persisting the values in the view is if you allow the user to type in some stuff, but then not commit it to the model and quit the application. And then when he re-runs the application you wish to pick up what he had typed into the widgets but not saved to the model. Is that what you want to achieve?

                      Not exactly. I want to open the programm, write name and points, than see it in the table and save it, and when i start the programm next time, see this information (name, points) again, instead of clear table

                      JonBJ Offline
                      JonBJ Offline
                      JonB
                      wrote on last edited by JonB
                      #10

                      @Lcashe
                      Then it sounds like you want to persist the model data, and reload it, not whatever happens to be in the QTableView. You do not need to save e.g. what is in a QLineEdit.

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

                        Then you might want to consider a simple SQLite database using Qt's SQL module.

                        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

                        • Login

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