如图所示,行索引与每行内容之间存在轻微的垂直偏移。我该如何解决这个问题?对了,怎样才能让行索引从1开始而不是从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)
我尝试调整字体大小和对齐方式,但都不起作用。