Skip to content
  • Categories
  • Recent
  • Tags
  • Popular
  • Users
  • Groups
  • Search
  • Get Qt Extensions
  • Unsolved
Collapse
Brand Logo
  1. Home
  2. Qt Development
  3. Qt for Python
  4. The QHeaderView has a slight vertical offset between the row index and the text in each row
Forum Updated to NodeBB v4.3 + New Features

The QHeaderView has a slight vertical offset between the row index and the text in each row

Scheduled Pinned Locked Moved Unsolved Qt for Python
4 Posts 3 Posters 340 Views 1 Watching
  • Oldest to Newest
  • Newest to Oldest
  • Most Votes
Reply
  • Reply as topic
Log in to reply
This topic has been deleted. Only users with topic management privileges can see it.
  • Z Offline
    Z Offline
    zhyemqww
    wrote on last edited by
    #1

    tempsnip.png
    As shown in the figure, there is a slight vertical offset between the row index and the contents of each column. 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)```
    S 1 Reply Last reply
    0
    • Z zhyemqww

      tempsnip.png
      As shown in the figure, there is a slight vertical offset between the row index and the contents of each column. 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)```
      S Offline
      S Offline
      StarterKit
      wrote on last edited by StarterKit
      #2

      Hi @zhyemqww
      This question is easy - "how can I make the row index start from 1 instead of 0?".
      In your headerData method your should return str(self._dataframe.index[section]) + 1 instead of str(self._dataframe.index[section]) for Qt.Orientation.Vertical.

      Wit regards to vertical offset... I think it depends on our OS and desktop theme being used. I may propose to use custom drawing but I think (and hope) it might be an overkill for this case. So I rather wait for more experienced people to comment on it. But.... I have one more suspect looking at your screenshot - you might use different fort for header than for data. So I would start with it - to check that fonts set for headers and body are the same.

      Z 1 Reply Last reply
      0
      • S StarterKit

        Hi @zhyemqww
        This question is easy - "how can I make the row index start from 1 instead of 0?".
        In your headerData method your should return str(self._dataframe.index[section]) + 1 instead of str(self._dataframe.index[section]) for Qt.Orientation.Vertical.

        Wit regards to vertical offset... I think it depends on our OS and desktop theme being used. I may propose to use custom drawing but I think (and hope) it might be an overkill for this case. So I rather wait for more experienced people to comment on it. But.... I have one more suspect looking at your screenshot - you might use different fort for header than for data. So I would start with it - to check that fonts set for headers and body are the same.

        Z Offline
        Z Offline
        zhyemqww
        wrote on last edited by
        #3

        @StarterKit When I modified the font for both the header and the body, keeping them consistent, the problem was not resolved.
        ![alt text](748e40f9-d031-4508-9877-46cad9755e4b-image.png image url)

        JonBJ 1 Reply Last reply
        0
        • Z zhyemqww

          @StarterKit When I modified the font for both the header and the body, keeping them consistent, the problem was not resolved.
          ![alt text](748e40f9-d031-4508-9877-46cad9755e4b-image.png image url)

          JonBJ Offline
          JonBJ Offline
          JonB
          wrote on last edited by
          #4

          @zhyemqww
          You may not like to hear this, especially being a Python developer, but I wonder if you might look at the source of how Qt positions the header's rows/columns to see if you can figure from that why it is "out of sync" wrt the content rows/columns.

          1 Reply Last reply
          0

          • Login

          • Login or register to search.
          • First post
            Last post
          0
          • Categories
          • Recent
          • Tags
          • Popular
          • Users
          • Groups
          • Search
          • Get Qt Extensions
          • Unsolved