使用QSortFilterProxyModel对QTreeView进行排序非常慢(与基本QTreeWidget相比)。代码有什么问题?我怎样才能加速?
# coding: utf-8
import sys
from PyQt5.QtWidgets import (QTreeView, QAbstractItemView,
QMainWindow, QApplication)
from PyQt5.QtSql import (QSqlDatabase, QSqlQuery, QSqlQueryModel)
from PyQt5.QtCore import QSortFilterProxyModel
class Database:
def __init__(self):
self.db = QSqlDatabase.addDatabase("QODBC")
self.db.setDatabaseName(
r'Driver={SQL Server Native Client 11.0};Server={(localdb)\v11.0};')
self.db.open()
class Model(QSqlQueryModel):
def __init__(self, parent=None):
super().__init__(parent)
query = QSqlQuery()
query.prepare('SELECT * FROM Companies WHERE Name LIKE ?')
query.bindValue(0, '%elektro%')
query.exec_()
self.setQuery(query)
class TreeView(QTreeView):
def edit(self, index, trigger, event):
if trigger == QAbstractItemView.DoubleClicked:
return False
return QTreeView.edit(self, index, trigger, event)
class Window(QMainWindow):
def __init__(self):
super().__init__()
self.db = Database()
self.model = Model()
sortFilterModel = QSortFilterProxyModel()
sortFilterModel.setSourceModel(self.model)
treeView = TreeView(self)
treeView.setModel(sortFilterModel)
treeView.hideColumn(0)
treeView.hideColumn(9)
treeView.setIndentation(0)
treeView.setSelectionMode(QAbstractItemView.MultiSelection)
treeView.setAllColumnsShowFocus(True)
treeView.setSortingEnabled(True)
treeView.clicked.connect(self.row_id)
self.setCentralWidget(treeView)
def row_id(self, index):
if index.isValid():
id_ = index.sibling(index.row(), 0).data()
print(id_)
if __name__ == '__main__':
app = QApplication(sys.argv)
window = Window()
window.show()
app.exec_()
答案 0 :(得分:1)
一些提示(从C ++的角度来看,所以我可能会遗漏一些东西)
QTreeView比QTableView和consume a lot of memory慢,而且你正在使用普通的表模型,所以,试试QTableview。
此外,在真正的树分层模型中,隐藏列0将隐藏所有子项。
尝试使用QSqlTableModel而不是QSqlQueryModel,它具有方便的setSort,setFilter方法,只能获取可见行。所以我可能会更快。