【问题标题】:QFileSystemModel remove folder from WatcherQFileSystemModel 从 Watcher 中删除文件夹
【发布时间】:2016-03-29 07:55:20
【问题描述】:

我在QTreeView 中使用了QFilesystemModel。每次我删除底层QFilesystemWatcher 监视的文件夹(例如通过shutils.rmtree())时,我都会收到此警告

QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: Datei oder Verzeichnis nicht gefunden
QFileSystemWatcher: failed to add paths: /path/to/deleted/folder

在我看来,这应该通过在使用 QFileSystemWatcher.removePath() 删除之前从 QFileSystemWatcher 删除文件夹来解决。但这不起作用,因为 seem to be no way to get in touchQFileSystemModel 中的 QFileSystemWatcher (我在没有运气的情况下寻找解决方案)。

那么有没有其他方法可以告诉QFileSystemModel 停止观看该文件夹?

PS:我知道我可以使用 QFileSystemModel.remove().rmdir() 来自动处理这个问题。但这不是我的选择。我需要从QFileSystemModel 之外删除该文件夹。

我在 Linux 上使用 Qt4 和 Python3。

【问题讨论】:

    标签: qt


    【解决方案1】:

    首先,QFileSystemModelQFileSystemWatcher 是两个不同的类。它们在任何方面都没有任何关系。 QFileSystemModel 不做监听,你自己添加文件监听器。

    顺便说一句,请注意QFileSystemModel::remove 只是删除文件。您仍然会收到错误消息。

    QFileSystemWatcher 深埋在QFileSystemModel 的代码下方,这就是您无法访问它的原因。

    编辑:

    但是,有一种简单的方法可以避免该警告。这是一个代码sn-p。我们假设有一个名为 /tmp/trial 的文件夹,其中包含一些文件。这是正在查看的文件夹,已从外部删除。

    ### == Code that creates a warning == ###
    
    # Initial state
    fsm = QFileSystemModel()
    lv = QListView()
    lv.setRootIndex( fsm.setRootPath( "/tmp/trial" ) )
    
    # External deletion of "/tmp/trial", leads to this error
    shutils.rmtree( "/tmp/trial" )
    # Error
       QInotifyFileSystemWatcherEngine::addPaths: inotify_add_watch failed: file or directory not found
       QFileSystemWatcher: failed to add paths: /tmp/trial
    
    
    ### == Suggested edit == ###
    
    # Initial state
    fsm = QFileSystemModel()
    lv = QListView()
    lv.setRootIndex( fsm.setRootPath( "/tmp/trial" ) )
    
    # Just before deleting
    lv.setRootIndex( fsm.setRootPath( "/tmp" ) )
    
    # External deletion of "/tmp/trial", gives no error
    # This even look very neat for the user.
    shutils.rmtree( "/tmp/trial" )
    

    为简单起见,我跳过了代理模型并使用了列表视图,但在您的情况下,代理模型和树视图的过程相同。

    【讨论】:

    • 谢谢。 QFileSystemModel 创建一个新的 QFileSystemWatcher 内部,不是吗?我还没有添加观察者,但显然有一个。那么它会从哪里来呢?或者我如何将新的QFileSystemWatcher 连接到模型?我在这两个类中都没有看到任何功能可以做到这一点。 QFileSystemModel 通过 QSortFilterProxyModelQTreeView 中使用。
    • 是的,你说得非常对,我正在查看源代码。然而,QFileSystemWatcher 内部使用深埋在代码下方,我们可能需要重型挖掘机才能找到它。 :D
    • 我很快就会在上面编辑我的答案。但这是你可以做的。如果您使用QFileSystemModel 显示文件和文件夹,我想您可以做什么,首先转到父目录,然后删除您之前显示的文件夹。这将消除观察者的错误。
    • 感谢您的精彩回答!
    猜你喜欢
    • 2014-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-05-23
    • 2013-06-28
    • 1970-01-01
    • 2013-12-10
    • 1970-01-01
    相关资源
    最近更新 更多