删除几行后,我尝试删除所有行,它变得非常慢

时间:2019-07-03 05:32:44

标签: python pyqt

最初,我创建一个QTableView,内部有很多行,然后使用QStandardItemModel来管理数据。启用按setSortingEnabled(True)排序。通过单击标题对数据进行排序后,我尝试删除所有行,但是速度非常慢。我用QSortFilterProxy解决了这个问题。但是我不知道为什么...

现在,另一个问题是: 如果我先删除服务器行,然后尝试选择并删除所有行,则会变得非常慢。


class Dialog(QDialog):
    def __init__(self, parent=None):
        super(Dialog, self).__init__(parent)
        self.setAttribute(Qt.WA_DeleteOnClose)
        self.setWindowTitle("Test")
        self._layout = QVBoxLayout(self)
        self._layout.setAlignment(Qt.AlignLeft)
        self.table = QTableView(self)
        self.table.setSortingEnabled(True)
        self.model = QStandardItemModel(self)

        for i in range(10000):
            lst = [QStandardItem('Test %s,%s' % (i, j)) for j in range(46)]
            self.model.appendRow(lst)

        sortProxy = QSortFilterProxyModel(self)
        sortProxy.setSourceModel(self.model)
        self.table.setModel(sortProxy)

        btLayout = QHBoxLayout()
        deleteBt = QPushButton(self)
        deleteBt.setText('Delete All')
        delete10 = QPushButton(self)
        delete10.setText('Delete 10 rows')
        deleteBt.clicked.connect(self.deleteRows)
        delete10.clicked.connect(self.delete10Rows)
        self._layout.addWidget(self.table)
        self._layout.addLayout(btLayout)
        btLayout.addWidget(deleteBt)
        btLayout.addWidget(delete10)
        btLayout.addStretch()

    def delete10Rows(self):
        self.table.model().removeRows(10, 10)

    # After delete 10 rows, then select and delete all rows, it's extremely slow
    # But if I delete all rows directly, the problem won't apear
    def deleteRows(self):
        selectModel = self.table.selectionModel()
        selectedRows = selectModel.selectedRows()
        if len(selectedRows) == 0:
            return

        selectedRows.sort(key=lambda x: x.row(), reverse=True)
        for index in selectedRows:
            self.table.model().removeRow(index.row())

if __name__ == '__main__':
    app = QApplication(sys.argv)
    main = Dialog()
    main.show()
    sys.exit(app.exec_())

0 个答案:

没有答案