[Python] QTableview in PySide6 calls data() multiple times for rows that should not be visible

Discussão em 'Python' iniciado por Stack, Novembro 26, 2025.

  1. Stack

    Stack Membro Participativo

    I have tested QTableview in pyside6 using the code below. When QTableview gets focus and we minimize the window when we restore the window suddenly the data() procedure can be called multiple times with role 10. I checked that role 10 is to check the status of the checkbox in the table. I don't use checkboxes in the table and the process of calling data() if there are many records stored in QTableview will make the program feel like it hangs/doesn't respond for a while. However, this incident is random and inconsistent. Sometimes it loops, sometimes it behaves normally.

    Has anyone else experienced the same thing? Is there a way to fix this?

    from PySide6.QtWidgets import QApplication, QMainWindow, QTableView, QStyleFactory
    from PySide6.QtCore import QAbstractTableModel, Qt
    import numpy as np

    class MyTableModel(QAbstractTableModel):

    def __init__(self, data):
    super().__init__()
    self._data = data

    def rowCount(self, parent=None):
    return len(self._data)

    def columnCount(self, parent=None):
    return len(self._data[0]) if self._data else 0

    def data(self, index, role=Qt.DisplayRole):
    print(index.row(), role)
    if role == Qt.DisplayRole:
    return self._data[index.row()][index.column()]
    return None

    def headerData(self, section, orientation, role=Qt.DisplayRole):
    if role == Qt.DisplayRole and orientation == Qt.Horizontal:
    return f"Column {section + 1}"
    return None

    class MainWindow(QMainWindow):

    def __init__(self):
    super().__init__()
    self.setWindowFlags(Qt.Widget)
    self.resize(800, 600)
    self.setWindowTitle("QTableView on pyside6 looping data() make slow")

    self.table_view = QTableView()
    data = [["Item A1", "Longer Item B1", "Item C1"] for _ in range(6000)]
    self.model = MyTableModel(data)
    self.table_view.setModel(self.model)

    self.setCentralWidget(self.table_view)

    if __name__ == "__main__":

    app = QApplication([])
    app.setStyle(QStyleFactory.create("Fusion"))
    window = MainWindow()
    window.setWindowFlags(Qt.Window)
    window.show()
    app.exec()

    Continue reading...

Compartilhe esta Página