0

enter image description here

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.

朱海洋
  • 21
  • 4
  • That stylesheet is most probably the culprit. Please provide a valid [mre]. – musicamante Aug 01 '23 at 14:41
  • @musicamante I have added a stylesheet, but in fact, I only modified the tableview's border and background color. – 朱海洋 Aug 01 '23 at 23:03
  • Setting generic QSS properties on complex widgets (like item views) is always discouraged, and [proper selector types](//doc.qt.io/qt-6/stylesheet-syntax.html#selector-types) should always be used instead. Besides, changing the border also results in altering the spacings between each section and the displayed text. Please take your time to fully review the [official QSS reference documentation](https://doc.qt.io/qt-6/stylesheet-reference.html) and the related examples. Keep in mind that style sheets are as powerful as they are difficult to master, especially if you need pixel-perfect results. – musicamante Aug 01 '23 at 23:19
  • Most importantly, you must keep in mind that item views are *composite* widgets. In the specific case of QTableView, it's actually made of: a QAbstractScrollArea subclass, which, in turn, contains a *viewport* (where items are actually placed and shown), two QScrollBars, and two QHeaderViews, each of them positioned and resized depending on the current style. A generic property such as `border: none;` will not only affect **all** the above widgets, but will reflect on the geometries of all those children, causing unwanted inconsistencies in the UI layout. – musicamante Aug 01 '23 at 23:23

0 Answers0