PyQt - Implement a QAbstractTableModel for display in QTableView

前端 未结 3 992
盖世英雄少女心
盖世英雄少女心 2021-02-07 08:48

I would like to display a pandas data frame in a PyQt table. I have made some progress with this, but have not been able to correctly derive the Table Model class. Any help with

相关标签:
3条回答
  • 2021-02-07 08:54

    Ok I have figured this one out with the above suggestion and some help from the Rapid GUI book by Summerfield. There is no underlying model that exists in the QAbstractTableModel. Only three functions need be overridden, and the data may be stored in any user defined format, as long as it is returned in the data call.

    A very simple implementation could be:

    class TableModel(QtCore.QAbstractTableModel): 
        def __init__(self, parent=None, *args): 
            super(TableModel, self).__init__()
            self.datatable = None
    
        def update(self, dataIn):
            print 'Updating Model'
            self.datatable = dataIn
            print 'Datatable : {0}'.format(self.datatable)
    
        def rowCount(self, parent=QtCore.QModelIndex()):
            return len(self.datatable.index) 
    
        def columnCount(self, parent=QtCore.QModelIndex()):
            return len(self.datatable.columns.values) 
    
        def data(self, index, role=QtCore.Qt.DisplayRole):
            if role == QtCore.Qt.DisplayRole:
                i = index.row()
                j = index.column()
                return '{0}'.format(self.datatable.iget_value(i, j))
            else:
                return QtCore.QVariant()
    
        def flags(self, index):
            return QtCore.Qt.ItemIsEnabled
    

    This enables you to view any compatable data frame in a Qt view.

    I have updated the Gist over here

    This should get you going quickly if you also need to do this.

    0 讨论(0)
  • 2021-02-07 09:11

    This is probably your problem:

    def rowCount(self, parent=QtCore.QModelIndex()):
        if type(self.datatable) == pd.DataFrame:
        ...
    
    
    def columnCount(self, parent=QtCore.QModelIndex()):
        if (self.datatable) == pd.DataFrame:
        ...
    

    You set your datatable to a QTableWidget in dataFrameToQtTable, so it can't be a pd.DataFrame, your methods will always return 0.

    Without the type check, you would have caught the problem immediately. Do you really want to silently ignore all cases where your type doesn't match (better let it raise an error if it doesn't follow the same interface you're expecting)? Typechecks are in most cases unnecessary.

    0 讨论(0)
  • 2021-02-07 09:13

    Pandas 0.13 provides as an experimental feature:

    PySide support for the qtpandas DataFrameModel and DataFrameWidget

    see https://github.com/pydata/pandas/blob/master/doc/source/faq.rst

    you can add this feature using

    from pandas.sandbox.qtpandas import DataFrameModel, DataFrameWidget
    
    0 讨论(0)
提交回复
热议问题