Search code examples
pythonscrollpyqt5qtableviewscrollto

How can i scroll to specific row in QTableView?


I want to scroll a spesific row in my table. My QTableView Model code is below.

class Customer(object):
    def __init__(self,name,number,status):
        self.name = name
        self.number = number
        self.status = status

class CustomerTableModel(QtCore.QAbstractTableModel):

    ROW_BATCH_COUNT = 1000

    def __init__(self):
        super(CustomerTableModel,self).__init__()
        self.headers = ['             İsim             ','  Telefon No (Örn 9053xx..)  ','   Mesaj Durumu   ']
        self.customers  = []
        self.rowsLoaded = CustomerTableModel.ROW_BATCH_COUNT

    def rowCount(self,index=QtCore.QModelIndex()):
        if not self.customers:
            return 0

        if len(self.customers) <= self.rowsLoaded:
            return len(self.customers)
        else:
            return self.rowsLoaded

    def addCustomer(self,customer):
        self.beginResetModel()
        self.customers.append(customer)
        self.endResetModel()

    def columnCount(self,index=QtCore.QModelIndex()):
        return len(self.headers)

    def data(self,index,role=QtCore.Qt.DisplayRole):
        col = index.column()
        customer = self.customers[index.row()]
        if role == QtCore.Qt.DisplayRole:
            if col == 0:
                return QtCore.QVariant(customer.name)
            elif col == 1:
                return QtCore.QVariant(customer.number)
            elif col == 2:
                return QtCore.QVariant(customer.status)
            return QtCore.QVariant()
        elif role == QtCore.Qt.TextAlignmentRole:
            return QtCore.Qt.AlignCenter

    def headerData(self,section,orientation,role=QtCore.Qt.DisplayRole):
        if role != QtCore.Qt.DisplayRole:
            return QtCore.QVariant()

        if orientation == QtCore.Qt.Horizontal:
            return QtCore.QVariant(self.headers[section])
        return QtCore.QVariant(int(section + 1))

I found a function for this problem but it works on QTableWidget. That I found code is below.

self.QtTableWidget.scrollToItem(item)

I can't use this function for QTableView. How can i do it? Any other functions?


Solution

  • In general for all the classes that inherit from QAbstractItemView(like QTableView, QTableWidget, QListView, etc) there is the scrollTo method that is used internally to scrollToItem:

    row = 4
    column = 0
    index = table_view.model().index(row, column)
    table_view.scrollTo(index)