As shown in the figure, there is a slight vertical offset between the row index and the contents of each row. How can I resolve this issue? By the way, how can I make the row index start from 1 instead of 0?
class PandasModel(QAbstractTableModel):
"""A model to interface a Qt view with pandas dataframe """
def __init__(self, dataframe: pd.DataFrame, parent=None):
QAbstractTableModel.__init__(self, parent)
self._dataframe = dataframe
def rowCount(self, parent=QModelIndex()) -> int:
""" Override method from QAbstractTableModel
Return row count of the pandas DataFrame
"""
if not parent.isValid():
return len(self._dataframe)
return 0
def columnCount(self, parent=QModelIndex()) -> int:
"""Override method from QAbstractTableModel
Return column count of the pandas DataFrame
"""
if not parent.isValid():
return len(self._dataframe.columns)
return 0
def data(self, index: QModelIndex, role=Qt.ItemDataRole) -> any:
"""Override method from QAbstractTableModel
Return data cell from the pandas DataFrame
"""
if not index.isValid():
return None
if role == Qt.ItemDataRole.DisplayRole:
return str(self._dataframe.iloc[index.row(), index.column()])
if role == Qt.ItemDataRole.TextAlignmentRole:
return Qt.AlignmentFlag.AlignLeft | Qt.AlignmentFlag.AlignVCenter # Set the alignment to Left
return None
def headerData(self, section: int, orientation: Qt.Orientation, role: Qt.ItemDataRole) -> any:
"""Override method from QAbstractTableModel
Return dataframe index as vertical header data and columns as horizontal header data.
"""
if role == Qt.ItemDataRole.DisplayRole:
if orientation == Qt.Orientation.Horizontal:
return str(self._dataframe.columns[section])
if orientation == Qt.Orientation.Vertical:
return str(self._dataframe.index[section])
return None
def creat_table(qtable_view, data):
qtable_view: QTableView
qtable_view.setStyleSheet(STYLE_SHEET["table_view"])
qtable_view.horizontalHeader().setStretchLastSection(True)
qtable_view.setAlternatingRowColors(True)
qtable_view.setSelectionBehavior(QTableView.SelectionBehavior.SelectRows) # Updated API
# Hide the row headers (vertical header)
# qtable_view.verticalHeader().setVisible(False)
model = PandasModel(data)
qtable_view.setModel(model)
This the style sheet dict
STYLE_SHEET = {
"button": "border: None; color: rgb(255, 255, 255); background-color: rgb(115, 149, 211);",
"button_pressed": "border: None; color: rgb(255, 255, 255); background-color: rgb(86, 127, 202);",
"table_view": "border:None;background-color: rgb(233, 245, 245);",
}
I tried adjusting the font size and alignment, but none of them worked.