如何在qfilesystemmodel中不进行过滤

发布于 2025-02-06 14:15:58 字数 2091 浏览 2 评论 0原文

以下代码运行(导入必要的库之后):

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MainWindow')
        self.layout = QHBoxLayout()
        self.file_system_widget = FileBrowser()
        self.layout.addWidget(self.file_system_widget)
        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)
   
class FileBrowser(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        layout = QVBoxLayout()
        self.model = QFileSystemModel()
        self.model.setRootPath(self.model.myComputer())
        self.model.setNameFilters(['*.*'])
        self.model.setNameFilterDisables(1)
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setAnimated(False)
        self.tree.setSortingEnabled(True)
        layout.addWidget(self.tree)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    try:
        os.mkdir('Imports')
    except:
        pass
    main = MainWindow()
    main.show()
    app.exec()

它在我的C驱动器上给出以下结果:

“在此处输入图像说明”

(此处提供了其中一些文件 https://drive.google.com/drive/forve/folders/folders/1ejyjy0cjy0cjfews6sgs6sgs6sgs2qe_urx2jvlrummkkvlrummkkkvpx)

我的目标是修改行self.model.setnamefilters(['*。*。*']),这样,在树视图中,它仅显示> dcm扩展名的文件以及没有扩展名的文件。也就是说,我绘制的红色部分被删除。

我如何实现这样的目标?为了保留dcm文件,我可以编写self.model.setnamefilters(['*。dcm'])之类的行,以保留它们并删除其他。但是我不确定如何在没有扩展的情况下处理文件或如何同时处理这两个要求。

The following code runs (after importing necessary libraries):

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MainWindow')
        self.layout = QHBoxLayout()
        self.file_system_widget = FileBrowser()
        self.layout.addWidget(self.file_system_widget)
        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)
   
class FileBrowser(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()
    
    def initUI(self):
        layout = QVBoxLayout()
        self.model = QFileSystemModel()
        self.model.setRootPath(self.model.myComputer())
        self.model.setNameFilters(['*.*'])
        self.model.setNameFilterDisables(1)
        self.tree = QTreeView()
        self.tree.setModel(self.model)
        self.tree.setAnimated(False)
        self.tree.setSortingEnabled(True)
        layout.addWidget(self.tree)
        self.setLayout(layout)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    try:
        os.mkdir('Imports')
    except:
        pass
    main = MainWindow()
    main.show()
    app.exec()

It gives the following result on my C drive:

enter image description here

(Some of these files are provided here https://drive.google.com/drive/folders/1ejY0CjfEwS6SGS2qe_uRX2JvlruMKvPX).

My objective is to modify the line self.model.setNameFilters(['*.*']) such that, in the tree view, it only shows files with dcm extension and also files without extension. That is, the part I draw red gets removed.

enter image description here

How do I achieve such a goal? For keeping dcm files, I can write lines like self.model.setNameFilters(['*.dcm']) to keep them and remove the others. But I am not sure how to deal with files without extension or how to deal with the two requirements at the same time .

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

故事未完 2025-02-13 14:15:58

qfilesystemmodel类仅支持基本的通配符过滤,因此您需要使用 qsortFilterProxymodel 进行完全可自定义的过滤。这将使您可以使用正则表达式进行过滤,从而实现您所需的大部分内容。但是,重现setNameFilterDisables的行为将需要重新实现代理模型的flags方法,并且分类也需要进行一些调整。

以下是基于您的示例的简单演示,它实现了所有这些:

“

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class FilterProxy(QSortFilterProxyModel):
    def __init__(self, disables=False, parent=None):
        super().__init__(parent)
        self._disables = bool(disables)

    def filterAcceptsRow(self, row, parent):
        index = self.sourceModel().index(row, 0, parent)
        if not self._disables:
            return self.matchIndex(index)
        return index.isValid()

    def matchIndex(self, index):
        return (self.sourceModel().isDir(index) or
                super().filterAcceptsRow(index.row(), index.parent()))

    def flags(self, index):
        flags = super().flags(index)
        if (self._disables and
            not self.matchIndex(self.mapToSource(index))):
            flags &= ~Qt.ItemIsEnabled
        return flags

class FileBrowser(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        self.model = QFileSystemModel()
        self.model.setFilter(
            QDir.AllDirs | QDir.AllEntries | QDir.NoDotAndDotDot)
        self.proxy = FilterProxy(True, self)
        self.proxy.setFilterRegularExpression(r'^(.*\.dcm|[^.]+)
)
        self.proxy.setSourceModel(self.model)

        self.tree = QTreeView()
        self.tree.setModel(self.proxy)
        self.tree.setAnimated(False)

        header = self.tree.header()
        header.setSectionsClickable(True)
        header.setSortIndicatorShown(True)
        header.setSortIndicator(0, Qt.AscendingOrder)
        header.sortIndicatorChanged.connect(self.model.sort)

        self.model.setRootPath(self.model.myComputer())
        root = self.model.index(self.model.rootPath())
        self.tree.setRootIndex(self.proxy.mapFromSource(root))

        layout.addWidget(self.tree)
        self.setLayout(layout)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MainWindow')
        self.layout = QHBoxLayout()
        self.file_system_widget = FileBrowser()
        self.layout.addWidget(self.file_system_widget)
        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec()

The QFileSystemModel class only supports basic wildcard filtering, so you will need to use a QSortFilterProxyModel to get fully customisable filtering. This will allow you to use a regular expression to do the filtering, which achieves most of what you want quite simply. However, reproducing the behaviour of setNameFilterDisables will require a reimplemention of the flags method of the proxy model, and the sorting will also need some adjustment.

Below is a simple demo based on your example that implements all of that:

screenshot

import sys
from PyQt5.QtCore import *
from PyQt5.QtWidgets import *

class FilterProxy(QSortFilterProxyModel):
    def __init__(self, disables=False, parent=None):
        super().__init__(parent)
        self._disables = bool(disables)

    def filterAcceptsRow(self, row, parent):
        index = self.sourceModel().index(row, 0, parent)
        if not self._disables:
            return self.matchIndex(index)
        return index.isValid()

    def matchIndex(self, index):
        return (self.sourceModel().isDir(index) or
                super().filterAcceptsRow(index.row(), index.parent()))

    def flags(self, index):
        flags = super().flags(index)
        if (self._disables and
            not self.matchIndex(self.mapToSource(index))):
            flags &= ~Qt.ItemIsEnabled
        return flags

class FileBrowser(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):
        layout = QVBoxLayout()
        self.model = QFileSystemModel()
        self.model.setFilter(
            QDir.AllDirs | QDir.AllEntries | QDir.NoDotAndDotDot)
        self.proxy = FilterProxy(True, self)
        self.proxy.setFilterRegularExpression(r'^(.*\.dcm|[^.]+)
)
        self.proxy.setSourceModel(self.model)

        self.tree = QTreeView()
        self.tree.setModel(self.proxy)
        self.tree.setAnimated(False)

        header = self.tree.header()
        header.setSectionsClickable(True)
        header.setSortIndicatorShown(True)
        header.setSortIndicator(0, Qt.AscendingOrder)
        header.sortIndicatorChanged.connect(self.model.sort)

        self.model.setRootPath(self.model.myComputer())
        root = self.model.index(self.model.rootPath())
        self.tree.setRootIndex(self.proxy.mapFromSource(root))

        layout.addWidget(self.tree)
        self.setLayout(layout)

class MainWindow(QMainWindow):
    def __init__(self):
        super().__init__()
        self.setWindowTitle('MainWindow')
        self.layout = QHBoxLayout()
        self.file_system_widget = FileBrowser()
        self.layout.addWidget(self.file_system_widget)
        widget = QWidget()
        widget.setLayout(self.layout)
        self.setCentralWidget(widget)

if __name__ == '__main__':

    app = QApplication(sys.argv)
    main = MainWindow()
    main.show()
    app.exec()
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文