2

i want to know how i can display a vertical header in a tableview. The vertical header should display the index.

I've created a dataframe of stock prices. The date is the index of the dataframe (i.e. 2017-12-06) and the close price is the value of the dataframe (i.e. 50$).

I wrote a model class that uses the QAbstractTabelModel. My headerData method is the following:

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

But there is no index in the displayed tableview.

Screenshot of the displayed TableView

The whole source code is the following:

from PyQt5 import QtCore

class PandasModel(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:
                return str(self._data.values[index.row()][index.column()])
        return None

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

I have the code from stackoverflow reference

Edit: My dataframe sourcecode attachement

dates = pd.date_range(start_date, end_date)
df = pd.DataFrame(index=dates)
df_temp = pd.read_csv(directory, index_col='Date', parse_dates=True, usecols=['Date', 'Adj Close'],
                      na_values=['nan'])
df = df.join(df_temp)
df = df.dropna(axis=0, how='any')
return df

Edit 2:

Screenshot of the csv file

eyllanesc
  • 235,170
  • 19
  • 170
  • 241
Neal Mc Beal
  • 245
  • 3
  • 16

1 Answers1

2

The problem is caused because the index returns a data type Timestamp that is not recognized by PyQt, the solution is to convert it to string, for this we have 2 possible options: use str() or the method strftime() indicating the format:

def headerData(self, rowcol, orientation, role=QtCore.Qt.DisplayRole):
    if orientation == QtCore.Qt.Horizontal and role == QtCore.Qt.DisplayRole:
        return self._data.columns[rowcol]
    if orientation == QtCore.Qt.Vertical and role == QtCore.Qt.DisplayRole:
        return self._data.index[rowcol].strftime('%Y-%m-%d') # or str(self._data.index[rowcol])
eyllanesc
  • 235,170
  • 19
  • 170
  • 241