sica07
sica07

Reputation: 4956

QTableView not updated on dataChanged

I'm not able to update the layout of a QTableView when the Model data is changed. I tried with dataChanged.emit(index,index), with layoutChanged.emit() and also, as a last resort, with reset(). None of it worked. My code:

class SettingsDialog(QDialog, settings_design.Ui_settingsDialog):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.weekdayTable = QTableView(self.weekdayPage)
        weekdayModel = self.loadMeetingData(self.meetingsData['weekdayList'])
      #weekdayModel.dataChanged.connect(self.updateTable)
        self.weekdayTable.setModel(weekdayModel)

    def updateTable(self):
        self.weekdayTable.repaint()

class MeetingsModel(QStandardItemModel):
    def __init__(self, data, columns):
        QStandardItemModel.__init__(self, data, columns)
        with open('meetings.config.json') as f:
            self.meetingsData = json.load(f)

    def setData(self, index, value, other):

        self.meetingsData['weekdayList'][int(index.row())][index.column()] = value
        with open('meetings.config.json', 'w+') as f:
            f.write(json.dumps(self.meetingsData))

        self.dataChanged.emit(index, index)
        # self.layoutChanged.emit(index, index)
        return True

What am I doing wrong?

Upvotes: 2

Views: 2466

Answers (1)

sica07
sica07

Reputation: 4956

I finally solved the problem by taking other approach.

Old approach (the elegant one):

I extended the QStandardModelItem's setData method with a function to save the modified data into a file.

New approach:

When the dataChanged signal is emitted by the QStandarItemModel the connected slot (writeChangedData) will write the changed data to the file. In other words, I moved the functionality from setData to the slot.

The code:

class SettingsDialog(QDialog, settings_design.Ui_settingsDialog):
    def __init__(self):
        super(self.__class__, self).__init__()
        self.setupUi(self)
        self.weekdayTable = QTableView(self.weekdayPage)
        self.weekdayModel = self.loadMeetingData(self.meetingsData['weekdayList'])
        self.weekdayModel.dataChanged.connect(self.writeModifiedData)
        self.weekdayTable.setModel(self.weekdayModel)

    def writeModifiedData(self, topLeft, bottomRight):
        self.weekdayModel['weekdayList'][int(topLeft.row())][topLeft.column()] = value
        with open('meetings.config.json', 'w+') as f:
            f.write(json.dumps(self.weekdayModel))
            f.close()

Upvotes: 1

Related Questions