QFileDialog View Files and Folders when choosing a Directory - qt

I'm new to learning the Qt library, and I'm having a hard time getting QFileDialog to work properly. I want the user to be able to select a directory but also be able to view the files and folders so they know which directory they should pick. I have seen things similar to this being posted elsewhere but everything I've tried hasn't made any difference in the output.
I've tried creating my own dialog and setting the mode to directory, which says that it should display both files and folders:
QFileDialog myDialog(this);
myFileExplorer.setFileMode(QFileDialog::Directory);
myFileExplorer.setDirectory("C:/");
QString file = myFileExplorer.exec();
And I've tried using getExistingDirectory as well, but with that function it always only shows the directory as well.
Thanks

QString getExistingDirectory ( QWidget * parent = 0, const QString & caption = QString(),
const QString & dir = QString(), Options options = ShowDirsOnly )
The default options parameter is set to show dirs only, you have to change it to
QFileDialog::DontUseNativeDialog
But unfortunately you won't be able to use native dialog.

Related

Pre-compile QML files under Qt Quick Controls

I am importing 2 QML files that come with Qt Controls - ScrollBar.qml and Button.qml in my project. I pre-compile all .qml files that I wrote to reduce application launch time. Is there a way to pre-compile these 2 QML files that come as part of the package?
I tried to remove these files from the qml/QtQuick/Controls/ path and placed them in the same folder as my .qml files but it still failed to load. When I reference ScrollBar in my code, it always tries to load ScrollBar.qml from qml/QtQuick/Controls/ path.
Does any one know if it is possible to pre-compile these QMLs at all? If yes, has any one successfully done it?
Appreciate any help. Thank you.
I'm assuming that you're referring to the Qt Quick Compiler as pre-compiling. The simplest way would just be to build the entire Qt Quick Controls module with the Qt Quick Compiler.
If you need to have it within your project, you could try adding an import that contains the Qt Quick Controls import. QQmlEngine::addImportPath() says:
The newly added path will be first in the importPathList().
That statement seems to imply that order matters, and the code confirms it:
QStringList localImportPaths = database->importPathList(QQmlImportDatabase::Local);
// Search local import paths for a matching version
const QStringList qmlDirPaths = QQmlImports::completeQmldirPaths(uri, localImportPaths, vmaj, vmin);
for (const QString &qmldirPath : qmlDirPaths) {
QString absoluteFilePath = typeLoader.absoluteFilePath(qmldirPath);
if (!absoluteFilePath.isEmpty()) {
QString url;
const QStringRef absolutePath = absoluteFilePath.leftRef(absoluteFilePath.lastIndexOf(Slash) + 1);
if (absolutePath.at(0) == Colon)
url = QLatin1String("qrc://") + absolutePath.mid(1);
else
url = QUrl::fromLocalFile(absolutePath.toString()).toString();
QQmlImportDatabase::QmldirCache *cache = new QQmlImportDatabase::QmldirCache;
cache->versionMajor = vmaj;
cache->versionMinor = vmin;
cache->qmldirFilePath = absoluteFilePath;
cache->qmldirPathUrl = url;
cache->next = cacheHead;
database->qmldirCache.insert(uri, cache);
*outQmldirFilePath = absoluteFilePath;
*outQmldirPathUrl = url;
return true;
}
}
Your project structure might look something like this:
myproject/
qml/
main.qml
QtQuick/
Controls/
Button.qml
ScrollBar.qml
qmldir
In main.cpp you'd set the path to the qml directory (note that the path will be different depending on whether you're doing an in-source build or a shadow build of your project, so you may want to use a resource file to simplify things):
engine.addImportPath("path/to/qml");
Note that the controls import other types. For example, Button uses the Settings singleton, which comes from the QtQuick.Controls.Private import, so you'd need to copy that into the qml directory, too. Settings loads a certain style for the button (ButtonStyle), which could be any of the styles in this folder, depending on which style is in use.
In short, you need to copy all of the potential dependencies of the QML files you're using.

How specify file filter in QFileDialog::getExistingDirectory?

I need to choose a directory with files "*.in".
But if i use getExistingDirectory, i can't specify file filter, so i can't see files.
But i need to see ONLY "*.in" files, i could be only choose a directory, not a file.
Now i use this code:
qDebug() << QFileDialog::getExistingDirectory(this, tr("Выберите папку с файлами устройств"), "", QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
And i can't see any files in chosen directory (in dialog).
How i can do this?
You need to pass QFileDialog::DontUseNativeDialog option. From the documentation of getExistingDirectory:
On Windows and OS X, this static function will use the native file
dialog and not a QFileDialog. However, the native Windows file dialog
does not support displaying files in the directory chooser. You need
to pass DontUseNativeDialog to display files using a QFileDialog. On
Windows CE, if the device has no native file dialog, a QFileDialog
will be used.
To filter displayed files by extension you will have to do slightly more:
QFileDialog dlg(nullptr, tr("Choose Directory"));
dlg.setOptions(QFileDialog::DontUseNativeDialog | QFileDialog::ShowDirsOnly | QFileDialog::DontResolveSymlinks);
dlg.setFileMode(QFileDialog::Directory);
dlg.setNameFilter(tr("Directories with device files (*.in)"));
if (dlg.exec())
qDebug() << dlg.selectedFiles();
When I tried this, the files that don't match the filter were still displayed, but in grey color (I tried on MacOS, maybe you will have more luck on Windows).
There is no standard way to prevent user from selecting a folder which contains no files matching the filter. A solution is to derive your own class from QFileDialog and override the accept function (not calling QFileDialog::accept from your override will prevent the dialog from closing).
I think it doesn't work with get-dir method. Would it be also acceptable to let the user select any of the *.in files and then getting the directory of that in-file using QFileInfo::path?
QString inFile = QFileDialog::getOpenFileName(
this,
tr( "Выберите папку с файлами устройств "
"выделив какой-либо из файлов устройств :-)"
),
lastSelectedDir,
"*.in"
);
QString dirName = QFileInfo(inFile ).absolutePath();

Folder browser dialog in Qt

Is there any way to open a folder browser dialog in Qt? When I use QFileDialog with Directory file mode, even if I specify the ShowDirsOnly option, I get the standard file dialog. I would prefer to use a dialog that asks the user to choose a directory from a directory tree.
Here's the PySide code I'm using:
from PySide import QtGui
app = QtGui.QApplication([])
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
dialog.exec_()
And here's the result I get on Windows 7:
It appears that the order in which you call setFileMode() and setOption() matters. Make sure you're calling setFileMode() first:
QFileDialog dialog;
dialog.setFileMode(QFileDialog::Directory);
dialog.setOption(QFileDialog::ShowDirsOnly);
...
I know, that my answer is some tricky and looks like little hack, but the QFileDialog static methods like getExistingDirectory() use the native dialog, so only limited customization is possible.
However, if you create a QFileDialog instance, you get a dialog that can
be customized -- as long as you're happy messing with a live dialog.
For example, this should show a tree view with expandable directories that
you can select (hope, it must be not a problem port this code to PySide):
QFileDialog *fd = new QFileDialog;
QTreeView *tree = fd->findChild <QTreeView*>();
tree->setRootIsDecorated(true);
tree->setItemsExpandable(true);
fd->setFileMode(QFileDialog::Directory);
fd->setOption(QFileDialog::ShowDirsOnly);
fd->setViewMode(QFileDialog::Detail);
int result = fd->exec();
QString directory;
if (result)
{
directory = fd->selectedFiles()[0];
qDebug()<<directory;
}
Got that method from here
Try this line of code, it show you a folder browse dialog:
ui->txtSaveAddress->setText(folderDlg.getExistingDirectory(0,"Caption",QString(),QFileDialog::ShowDirsOnly));
This worked for me:
def getDir(self):
dialog = QtGui.QFileDialog()
dialog.setFileMode(QtGui.QFileDialog.Directory)
dialog.setOption(QtGui.QFileDialog.ShowDirsOnly)
directory = dialog.getExistingDirectory(self, 'Choose Directory', os.path.curdir)

Save the screenshot of a widget

I want to save a screenshot of a widget in Qt.
I created the following code that should work:
QWidget* activeWidget = getActiveWidget();//a function that returns the current widget.
if (activeWidget == NULL)
{
return;
}
QPixmap screenshot;
screenshot = QPixmap::grabWidget(activeWidget,activeWidget->rect());
if(screenshot.isNull()){
printf("ERROR");
}
bool a= screenshot.save("c:\\temp\\asd.jpg", "JPG", 50);
But unfortunately this does not seem to work.
Does anyone know what the problem is?
In this answer and this forum post, people suggest the following:
Most likely, the plugin which is required to handle .jpg files is not found by your application. In order to resolve this issue, do one of the following things:
If you are doing a static build, add QTPLUGIN += qjpeg to your .pro file or
if you are doing a dynamic build, put the imageformats folder from %QTDIR%\plugins next to your .exe

QFileDialog::getExistingDirectory does not close after choosing a folder

In Qt,
QFileDialog *dlg = new QFileDialog();
QDir dir = dlg->getExistingDirectory(this, tr("Choose folder"), qgetenv("HOME"));
opens a folder choose dialog. Once I select a folder (press choose button) the folder is not closing automatically. So I tried:
if(dlg->close() == true) delete(dlg);
When I debug the dlg->close() returns true and the code delete(dlg) is hit. Still the Folder chooser dialog box is not closing.
I am using Ubuntu 11.10 64 bit OS. Using Qt libraries from the repository.
My ultimate aim is just to show a folder chooser dialog and once the folder is chosen the dialog should close. After that processing should continue. How to do this?
Thanks in advance.
Even if QFileDialog::getExistingDirectory is static and doesn't need a QFileDialog object to work, it should close the dialog window when a directory is finally chosen.
By default that function tries to open a native file dialog window, which seems to cause some problems on some platforms.
You should try forcing a non-native dialog by adding the option DontUseNativeDialog:
QString dir = QFileDialog::getExistingDirectory(
this,
tr("Choose folder"),
QDesktopServices::storageLocation(QDesktopServices::HomeLocation),
QFileDialog::ShowDirsOnly | QFileDialog::DontUseNativeDialog);
And remove the two other lines (with new QFileDialog and if(dlg->close()) ...).
getExistingDirectory(...) is a static function.
To add to cmannett85's answer:
You should not make an instance of QDialog. If you do, it's up to you to hide it. Modify your code to read
const QString home = QDesktopServices::storageLocation(QDesktopServices::HomeLocation);
const QDir dir = QFileDialog:getExistingDirectory(this, tr("Choose folder"), home);
This code should be relatively portable. qgetenv("HOME") is Unix-specific. You should not introduce gratuituous platform-specific code in Qt-based projects -- it sort of defeats the purpose of using Qt in the first place.

Resources