QFileDialog: Selecting directories and files - c++

I'm using the code below to build a qstringlist of filenames:
QStringList filenames = QFileDialog::getOpenFileNames(this,"",QDir::currentPath() );
How can I change this so I can select directories as well?
I looked at:
dialog.setFileMode(QFileDialog::AnyFile);
but I don't get how to use it with my code.

This code snippet linked in the comment above solves my issue.
QFileDialog* _f_dlg = new QFileDialog(this);
_f_dlg->setFileMode(QFileDialog::Directory);
_f_dlg->setOption(QFileDialog::DontUseNativeDialog, true);
// Try to select multiple files and directories at the same time in QFileDialog
QListView *l = _f_dlg->findChild<QListView*>("listView");
if (l) {
l->setSelectionMode(QAbstractItemView::MultiSelection);
}
QTreeView *t = _f_dlg->findChild<QTreeView*>();
if (t) {
t->setSelectionMode(QAbstractItemView::MultiSelection);
}
int nMode = _f_dlg->exec();
QStringList _fnames = _f_dlg->selectedFiles();

I tried this, but the result in my case is a bit strange: I can select a combination of folders and files, as long as the first selected item is a folder.
So when I select a folder, then a file and again a folder, I can proceed clicking the button and retrieving the results: see screenshot in link below.
First folder selected, then file: OK
However, when the first item is a file (followed by a folder, or just a file), the button to proceed is not available... So just selecting one or multiple files is not available to me in this implementation it seems, as can be seen in the other screenshot:
First file selected, then folder: not able to proceed
Is there any way using the same code using QFileDialog that allows you to
select one or more files without selecting folders
selecting one or more folders without selecting files
selecting a combination of files and folders regardless of selection order

Related

QFile: directory not found

I need to write a console application that takes a file, it opens it, and then it calls another procedure based on the information inside the text file.
The only problem is that QFile::errorString() returns:
No such file or directory.
I have been using this implementation in all the programs I had to, and yes, the file exists at that directory.
The code is:
QFile fileName("D:/file.txt");
QString read_from_file;
if(fileName.open(QIODevice::ReadOnly)){
QTextStream in(&fileName);
while(!in.atEnd())
{
read_from_file = in.readLine();
qDebug()<<read_from_file;
}
fileName.close();
}
qDebug()<<fileName.errorString();
Make sure that the file really exists.
QFile::exists("D:/file.txt") – This will return true if the file exists.
QDir("D:/").entryList() – This will return the list of the files and directories located at the specified path; the needed file should be in the list.
As you pointed out in the comments, the problem was the hidden file extensions on Windows.
Open Folder Options by clicking the Start button, clicking Control Panel, clicking Appearance and
Personalization, and then clicking Folder Options.
Click the View tab, and then Advanced settings <...>
To show file name extensions, clear the Hide extensions for known file
types check box, and then click OK.

Filtering based on file extension not working in QFileSystemModel?

I am trying to filter file system model to show only files with extension .ncr (NCReport templates). The view instead shows all files. Any ideas how to make the filtering work? Thanks.
(I realize there's plenty other clumsiness here, suggestions welcome.)
fsmodel = new QFileSystemModel(this);
connect(fsmodel,SIGNAL(rootPathChanged(QString)),this,SLOT(fileSystemModelRootSetSuccessfully()));
// this call is required on windows to show anything in file view
QModelIndex rootIndex=fsmodel->setRootPath(reportdirstring);
// root index could be removed
Q_UNUSED(rootIndex);
fsmodel->setReadOnly(true);
ui->reportTemplateDirView->setModel(fsmodel);
ui->reportTemplateDirView->setRootIndex(fsmodel->index(reportdirstring));
ui->reportTemplateDirView->expandAll();
ui->reportTemplateDirView->header()->hide();
// selecting the first file entry with selectFileInDirView(); requires the qtreeview to be sorted
// sort in desc order since that is the only way to get the first item selected?
ui->reportTemplateDirView->sortByColumn(0,Qt::AscendingOrder);
fsmodel->sort(0,Qt::AscendingOrder);
QStringList filters;
filters << "*.ncr";
fsmodel->setNameFilters(filters);
fsmodel->setNameFilterDisables(false);
// hide report template directory view extra columns,
//type?
ui->reportTemplateDirView->setColumnHidden(1,true);
//size?
ui->reportTemplateDirView->setColumnHidden(2,true);
//date
ui->reportTemplateDirView->setColumnHidden(3,true);
#if QT_VERSION >= 0x040700
// as soon as QFileSystemModel has parsed the entire directory tree, tell the QTreeView to expand its hierarchy
// note that if there are a lot of files, this could be too inefficient.
// if problems arise, consider commenting this out or using a QDirModel, which could be equally inefficient though.
connect(fsmodel,SIGNAL(directoryLoaded(QString)),ui->reportTemplateDirView,SLOT(expandAll()));
connect(fsmodel,SIGNAL(directoryLoaded(QString)),this,SLOT(selectFileInDirView()));
#endif
// show a fake folder name + icon at the top of the folder tree of report template directory
QFileIconProvider iconProvider;
QIcon folderIcon=iconProvider.icon(QFileIconProvider::Folder);
ui->reportTemplatesLabel->setPixmap(QPixmap(folderIcon.pixmap(QSize(16,16))));
As Alexander noted, this actually works. The issue was that I was setting the filters to empty elsewhere. ^.^

QFileDialog showing hidden files although system setting is off

I am using the following code to show an open dialog in Qt:
QString path = QFileDialog::getOpenFileName(this, tr("Open Config File"), QDir::rootPath(), "Text Files (*.txt *.csv *.*);;");
What I realised is that this dialog also shows hidden files although the system setting for showing hidden files is turned off. It's the same if I instantiate the QFileDialog manually and show it. I also couldn't find out how to turn this off via a filter.
Does anyone know if there is a way to achieve the desired behaviour?
Looks like there is no simple(by setting some flag) solution out there. So I recommend to use the filtering which is described in other SO answer.
But in your case you might use the following condition:
if(fileModel != nullptr)
{
QFileInfo info = fileModel->fileInfo(index0);
return info.isHidden();
}
return false;

Qt remembering the last open folder

I am using QFileDialog::openfilename for taking a file from user as input and I have specified the default folder which is to be shown when user open dialog.
But qt is somehow remembering the last open folder when filedialog is opened multiple times. But I want the default folder to be the the initial folder shown to the user not the last opened folder. In this, I am doing nothing explicitly to store the last opened information anywhere.
Please tell me what is the problem here and how to fix this.
It is clearly documented here. The third parameter to getOpenFileName is dir.
The file dialog's working directory will be set to dir. If dir includes a file name, the file will be selected.
Use this. setDirectory(str); install default path and you never get the last opened directory.
void MainWindow::on_pushButton_clicked()
{
QFileDialog dia;
dia.setDirectory("D:/");//or another default folder
QString path1 = dia.getOpenFileName(this,"Choose file");
}
Try Qsettings with rewritting them down, you'll need a initialize with param path
void camera_index::writesetting_window() {
//camera_index page
QSettings settings("Moose Soft", "Clipper");
settings.setValue("set_FOCUS", ui->camera_focus->value());
}
void camera_index::readsetting_window() {
QSettings settings("Moose Soft", "Clipper");
int FOCUS = settings.value("set_FOCUS").toInt();}
basically just set a fix value would help

QFileSystemModel and QTreeView - strange behavior when resetting view

I wrote this on official forums of Qt, but it seems dead, so I am going to copy-paste it here.
I am writing small program for copying files. I use QTreeView and I have inherited from QFileSystemModel, so I was able to add checkboxes to every row in the QTreeView. I also use setNameFilters method connected with QLineEdit, so user can specify what file extensions he wants to display in the QTreeView. I have spotted the following behavior:
1) When I run the program and enter extensions to filter (without touching any node from the QTreeView) everything works fine and files with extensions I have provided are only displayed (and folders of course). When I change the extensions and the view is refreshed, on my "C:/" drive everything is updated and only new set of extensions is displayed. When I expand some other drive that I didn’t touch before, it also shows files correctly.
2) When I run the program and expand let say my "C:/" and "D:/" drives I see all directories and files (expected behavior). Then I write some extensions and the view is refreshed. I expand "C:/" drive and everything works fine, only files with extensions I have provided are displayed. Then I go to "D:/" drive and here is the problem. It displays all files. It ignores the filters I have provided. When I open the "E:/" drive that I have not opened before, the files are filtered correctly as in "C:/" drive.
I have concluded, that this behavior has something to do with setRootPath method, because for my QTreeView only in "C:/" drive the filters are working correctly. All other drives that were expanded before change of filters don’t work. Those not expanded work just fine.
The question is: How to get this working, so after user changes the filters and reset() method is fired, the whole QTreeView is refreshed and not only root path and not-expanded elements? Maybe there exists some root path that have all the drives as children and it will work as expected? Or maybe I should make some virtual folder in the QTreeView called "MyComputer" and set it to be a parent for all the drives? But how to get list of all the available drives?
I hope that what I wrote is clear for you and you can help me to get this working.
Edit:
Adding some code that is relevant. If you need more just ask.
//setting up the model and view
QString rPath = "C:/";
rTree_model = new TreeModel(this); //TreeModel inherits from QFileSystemModel
rTree_model->setRootPath(rPath);
ui->rTree->setModel(rTree_model); //applies the model for the qtreeview (ui->rTree)
//(...)
//action when extensions were provided by user
QString extensions = QString(ui->extensionBox->text()); //gets extensions provided by user
QStringList filters;
if(extensions.length() > 0) {
filters = extensions.split(";", QString::SkipEmptyParts); //splits extensions provided with ';' as separator
rTree_model->setNameFilters(filters); //applies filters
ui->rTree->reset(); //resets the view
}
Try changing your root path to My Computer instead of C:/. It seems to work with QFileSystemModel in Windows 7 x64 and Qt 4.8.2, but I can't guarantee anything for other platforms.
rTree_model = new TreeModel(this);
QString rPath = model->myComputer().toString(); //causes the QFileSystemWatcher to watch every drive?
rTree_model->setRootPath(rPath);
ui->rTree->setModel(rTree_model);