You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在QFileDialog中先过滤目录再设置文件名过滤规则

QFileDialog目录过滤异常及文件过滤需求

问题背景

想要实现一个QFileDialog,限制用户仅能从公共目录下的特定目录中选择文件,同时后续还需要按另一规则筛选文件名。尝试过基于QSortFilterProxyModel的目录过滤方案,但未达到预期效果。

当前实现代码

自定义代理模型代码

class FileFilterProxyModel : public QSortFilterProxyModel
{
protected:
    virtual bool filterAcceptsRow(int row, const QModelIndex &parent) const;
};

bool FileFilterProxyModel::filterAcceptsRow(int row, const QModelIndex &parent) const
{
    QModelIndex index0 = sourceModel()->index(row, 0, parent);
    QFileSystemModel *fileModel = qobject_cast<QFileSystemModel*>(sourceModel());

    if ((fileModel != NULL) && (fileModel->isDir(index0)))
    {
        if (fileModel->fileName(index0).startsWith("di_"))
        {
            return true;
        }
        else
        {
            return false;
        }
    }
    else
    {
        return false;
    }
}

调用代码

QFileDialog dialog;
FileFilterProxyModel *proxyModel = new FileFilterProxyModel;

dialog.setProxyModel(proxyModel);
dialog.setOption(QFileDialog::DontUseNativeDialog);
dialog.setDirectory(directoryName);
dialog.setFileMode(QFileDialog::ExistingFile);
dialog.exec();

异常现象

  • 应用上述代理模型后,QFileDialog未显示任何符合以"di_"开头规则的目录(实际符合规则的目录存在)
  • 添加qDebug调试后,仅输出指定根目录的路径条目
  • 若将fileModel->fileName(index0).startsWith("di_")的返回逻辑反转(符合规则返回false,不符合返回true),则能正常显示所有非"di_"开头的目录,符合预期
  • 无法理解为何修改前缀检查的返回值会完全改变被检查的目录范围

后续需求

解决目录过滤的异常问题后,还需要按另一规则筛选文件名,询问是否可以通过当前的FileFilterProxyModel实现,还是需要其他方法。

更新说明

感谢@C137的帮助,已成功显示目标目录,并通过以下代码实现了文件过滤:

dialog.setNameFilter("<enter filter here>");

内容的提问来源于stack exchange,提问作者DesertBroncoFan

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 09:30:51