Home > Enterprise >  adding row number to QTableView in pyside2
adding row number to QTableView in pyside2

Time:07-20

is there any way I could add a row number beside the QTableView just for info and not actually add it into the data so that I could export it without the row number as a new column? it seems like everyone has it on default while mine is not showing at all. i tried tableView.verticalHeader().setVisible(True) but it isn't working. looked everywhere in the docs also wasn't mentioned, maybe I missed it

enter image description here

here's what I've tried so far

from PySide2.QtWidgets import *
from PySide2.QtGui import *
from PySide2.QtCore import *
import pandas as pd

class MyWindow(QWidget):
    def __init__(self, parent=None, data=None):
        QWidget.__init__(self, parent)
        self.setGeometry(300, 200, 570, 450)
        self.setWindowTitle('MyWindow')
        data = {'name': ['abdul','budi','cindy'],'ID':[1,2,3], 'balance': [100,200,300]}
        df = pd.DataFrame(data)
        self.model = PandasModel(df)
        self.table_view = QTableView()
        self.table_view.setModel(self.model)
        layout = QVBoxLayout(self)
        layout.addWidget(self.table_view)
        self.setLayout(layout)
        self.table_view.verticalHeader().setVisible(True)
        self.table_view.verticalHeader().show()

class PandasModel(QAbstractTableModel):
    """
    Class to populate a table view with a pandas dataframe
    """
    def __init__(self, data, parent=None):
        QAbstractTableModel.__init__(self, parent)
        self._data = data

    def rowCount(self, parent=None):
        return self._data.shape[0]

    def columnCount(self, parent=None):
        return self._data.shape[1]

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

    def headerData(self, col, orientation, role):
        if orientation == Qt.Horizontal and role == Qt.DisplayRole:
            return self._data.columns[col]
        return None

if __name__ == "__main__":
    app = QApplication([])
    UI = MyWindow()
    UI.show()
    sys.exit(app.exec_())

CodePudding user response:

You can just return the row number in your headerData implementation like:

QVariant MyTable::headerData(int section, Qt::Orientation orientation, int role = Qt::DisplayRole) const
{
    if (orientation == Qt::Vertical && role == Qt::DisplayRole)
        return section;
    return QAbstractItemModel::headerData(section, orientation, role);
}

CodePudding user response:

The python approach from result image

  • Related