QFileDialog: is it possible to filter only executables (under Linux)?
我想使用QFileDialog让用户选择一个可执行文件。除目录外,该对话框应仅显示实际的可执行文件。
我的Windows版本工作正常,只需检查扩展名是否为exe。但是,在Linux中,我无法按照自己的意愿进行操作。
在C ++中,我的尝试如下所示:
1 2 3 4 | QString target_dir = ... QFileDialog file_dialog; file_dialog.setFilter(QDir::Executable | QDir::Files); QString file = file_dialog.getOpenFileName(this, tr("Open Exectuable"), target_dir); |
但是,此代码导致显示所有文件。
我尝试添加其他过滤器,但到目前为止没有任何效果。在StackOverflow上已经存在两个与我的问题基本相同的问题,但都没有实际答案:
在Linux上的QFileDialog中过滤可执行文件
使用QFileDialog仅显示Ubuntu上的目录和可执行文件
有人知道该怎么做吗?还是QFileDialog根本无法做到这一点?可以做到吗?或者识别可执行文件通常不是那么简单?
(注意:我使用Qt 4.8.5,因为我使用了与Qt 5不兼容的第三方代码)。
(注意:由于它也与Python相关,因此未将其标记为C ++。)
对文件对话框使用代理模型。
就我而言,代码如下:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 | #include <QSortFilterProxyModel> #include <QFileSystemModel> // Custom proxy for filtering executables class FileFilterProxyModel : public QSortFilterProxyModel { private: virtual bool filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const; }; bool FileFilterProxyModel::filterAcceptsRow(int sourceRow, const QModelIndex &sourceParent) const { QFileSystemModel* fileModel = qobject_cast<QFileSystemModel*>(sourceModel()); QFileInfo file( fileModel->filePath(sourceModel()->index(sourceRow, 0, sourceParent)) ); if (fileModel!=NULL && file.isExecutable()) return true; else return false; } // usage of proxy model QFileDialog dialog( this, tr("Choose a file")); FileFilterProxyModel* proxyModel = new FileFilterProxyModel; dialog.setProxyModel(proxyModel); dialog.setOption(QFileDialog::DontUseNativeDialog); // required by proxy model if( dialog.exec() == QDialog::Accepted ) { ... } |
这显示了在Linux和Windows(Qt 4.8.6)上都经过测试的可执行文件和文件夹。
完整资料
如果使用本机文件对话框,则某些设置无效。
这应该工作:
1 2 3 | QFileDialog dlg(this, tr("Select executable")); dlg.setOption(QFileDialog::DontUseNativeDialog, true); dlg.setFilter(QDir::Executable | QDir::Files); |
请注意,这只会过滤可执行文件。 要同时显示文件夹,没有已知的解决方案。