Editable QTableView and Pandas do not work properly

前端 未结 2 396
隐瞒了意图╮
隐瞒了意图╮ 2021-01-20 15:08

I am trying to get a self-contained piece of example code for using pandas and QTableView while getting editable cell views.

For this I am following up to an earlier

2条回答
  •  忘掉有多难
    2021-01-20 15:32

    It seems to work when I switch to PySide instead of PyQt4:

    import sys
    from PySide import QtCore, QtGui
    import pandas as pd
    Qt = QtCore.Qt
    
        class PandasModelEditable(QtCore.QAbstractTableModel):
        def __init__(self, data, parent=None):
            QtCore.QAbstractTableModel.__init__(self, parent)
            self._data = data
    
        def rowCount(self, parent=None):
            return len(self._data.values)
    
        def columnCount(self, parent=None):
            return self._data.columns.size
    
        def data(self, index, role=QtCore.Qt.DisplayRole):
            if index.isValid():
                if role == QtCore.Qt.DisplayRole or role == QtCore.Qt.EditRole:
                    return unicode(self._data.iloc[index.row(), index.column()])
            return None
    
        def headerData(self, section, orientation, role=QtCore.Qt.DisplayRole):
            if role != QtCore.Qt.DisplayRole:
                return None
            if orientation == QtCore.Qt.Horizontal:
                try:
                    return '%s' % unicode(self._data.columns.tolist()[section])
                except (IndexError,):
                    return unicode()
            elif orientation == QtCore.Qt.Vertical:
                try:
                    return '%s' % unicode(self._data.index.tolist()[section])
                except (IndexError,):
                    return unicode()
    
        def flags(self, index):
            return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsSelectable | \
                   QtCore.Qt.ItemIsEditable
    
        def setData(self, index, value, role=QtCore.Qt.EditRole):
            if index.isValid():
                self._data.iloc[index.row(), index.column()] = value
                if self.data(index, QtCore.Qt.DisplayRole) == value:
                    self.dataChanged.emit(index, index)
                    return True
            return False
    
    
    if __name__ == '__main__':
        application = QtGui.QApplication(sys.argv)
        view = QtGui.QTableView()
        df = pd.DataFrame([[1, 2, 3], [4, 5, 6]], columns=['a', 'b', 'c'], index=['x', 'y'])
    
        model = PandasModelEditable(df)
        view.setModel(model)
    
        view.show()
        sys.exit(application.exec_())
    

提交回复
热议问题