How to make QFileDialog return a directory or a filename in one method
Just got into a problem wherein I need to select a file or a directory using QFileDialog. There are existing static methods like getExistingDirectory() and getOpenFileName(), however, they work separately. How can I make QFileDialog support both behaviors in one method?
AFAIK, you can't do that without hacking Qt's sources yourself. Building the dialog yourself would not help since there's no mode (see setFileMode) that correspond to what you need.
This is an unusual thing to do.
What's your usecase for that, because I don't think it would be intuitive for a user. Maybe something else would be better here?
I'm creating an IDE for a work "stuff" (let's call is stuff).
In here, a project can be a file or a folder [the usecase].
I made a simple workaround using pyside:
from PySide import QtCore, QtGui
def __init__(self, *args): super(FileDialog, self).__init__(*args) self._selected = "" self.currentChanged.connect(self._onCurrentChanged) @QtCore.Slot(unicode) def _onCurrentChanged(self, path): # path becomes empty when file is selected # triggered twice if path: self._selected = path self.selectFile(path) def accept(self): self.done(1) super(FileDialog, self).accept() def getSelected(self): return self._selected @staticmethod def getFileOrDirectory(parent): dialog = FileDialog(parent) result = dialog.exec_() if result: return dialog.getSelected() return ""
Could you pls verify it?
Maybe, I'll try to rewrite in C++ later.
I had to do something very similar recently. The user could choose either a directory or a single file (importing maps into a situational awareness application). Some maps (OSM tiles for example) are most easily imported by choosing the directory they are in. Others (GeoTIFFs), by picking the map file.
I didn't want to have separate "Import GeoTIFF", "Import OSM tiles", "Import ADRG", "Import CADRG", etc commands.
I used a TreeView with a QFileSystemModel.