更改Model数据后,我无法更新QTableView的布局。
我尝试使用dataChanged.emit(index,index),layoutChanged.emit()以及最后一次使用reset()的方法。没有一个起作用。
我的代码:

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


我究竟做错了什么?

最佳答案

我终于通过其他方法解决了这个问题。

旧方法(优雅的方法):

我扩展了QStandardModelItemsetData方法,该函数具有将修改后的数据保存到文件中的功能。

新的方法:

dataChanged发出QStandarItemModel信号时,连接的插槽(writeChangedData)会将更改后的数据写入文件。换句话说,我将功能从setData移到了插槽。

代码:

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()

10-08 11:40