[英]PyQt5: phantom columns when using QTableView.setSortingEnabled and QSortFilterProxyModel
[英]QTableView + QFileSystemModel not sorting when setSortingEnabled(True)
考虑以下代码段:
import sys
import os
import time
from PyQt5.Qt import * # noqa
class Foo(QTableView):
def __init__(self, path, extensions, parent=None):
super().__init__(parent)
model = QFileSystemModel(self)
model.setRootPath(QDir.rootPath())
model.setFilter(QDir.NoDotAndDotDot | QDir.Files)
model.setNameFilterDisables(False)
self.setModel(model)
self.setShowGrid(False)
self.verticalHeader().hide()
self.setSelectionBehavior(QAbstractItemView.SelectRows)
self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Fixed)
self.setSelectionMode(QAbstractItemView.SingleSelection)
self.change_path(path)
self.setSortingEnabled(True)
def change_path(self, path):
model = self.model()
index = model.index(str(path))
self.setRootIndex(model.index(os.path.dirname(str(path))))
self.scrollTo(index)
self.setCurrentIndex(index)
def main():
app = QApplication(sys.argv)
file_view = Foo(__file__, ["*.*"])
file_view.show()
sys.exit(app.exec_())
if __name__ == "__main__":
main()
由于某些原因,当我单击标题时,行将不被排序,这是为什么呢?
Docs说:
QTableView :: setSortingEnabled(bool enable)如果enable为true,则启用对表的排序,并立即使用当前的sort节和order触发对sortByColumn()的调用。注意:属性sortingEnabled的Setter函数。 另请参见isSortingEnabled()。
在这种情况下,主要问题是QDir.rootPath()
默认情况下提供C:/
,而我正在使用的初始路径位于D:
,因此要使其正常工作,您需要确保setRootPath会匹配初始路径:
即:通过model.setRootPath('D:/')
更改model.setRootPath(QDir.rootPath())
model.setRootPath('D:/')
,它将正常工作。 甚至更好的是,从初始路径中提取字母,以免对任何内容进行硬编码。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.