mcast
mcast

Reputation: 1

How to create a proper QAbstractTableModel subclass from PyQt5 for a pandas dataframe?

I have coded up this custom subclass for my project based on the multiple refrences online however when I run my project I get an empty window.

class TableModel(QAbstractTableModel):
    def __init__(self, data):
        super().__init__()
        self._data = data

    def data(self, index, role=Qt.ItemDataRole.DisplayRole):
        if index.isValid:
            if role == Qt.ItemDataRole.DisplayRole:
                value = self._data.iloc[index.row(), index.column()]
                return str(value)

    def rowCount(self, index):
        return self._data.shape[0]

    def columnCount(self, index):
        return self._data.shape[1]

    def headerData(self, section, orientation, role=Qt.ItemDataRole.DisplayRole):
        # section is the index of the column/row.
        if role == Qt.ItemDataRole.DisplayRole:
            if orientation == Qt.Orientation.Horizontal:
                return str(self._data.columns[section])

            if orientation == Qt.Orientation.Vertical:
                return str(self._data.index[section])
class DataWindow(QWidget):
    def __init__(self):
        super().__init__()

        self.setWindowTitle("title")

        self.table = QTableView()
        self.data = pd.DataFrame()

        self.model = TableModel(self.data)
        self.table.setModel(self.model)
        self.table.resize(800,600)
    
    def display_table(self):
        self.show()

I have modified the following sections.

Qt.ItemDataRole.DisplayRole Qt.Orientation.Horizontal

I saw that many of them tried to use Qt.Horziontal or Qt.DisplayRole however they are no longer supported that way. I have used PyQt5 documentation to avoid having any errors but I don't get a pandas dataframe showing on the window. I have yet to find any solution thats up to date online.

Upvotes: 0

Views: 29

Answers (0)

Related Questions