Question

I want to store a selected file's location as a string in Python. I am trying to use QFileDialog to accomplish this, I have:

self.filedialog = QtGui.QFileDialog(self)
self.filedialog.show()
filepath = str(self.filedialog.getOpenFileName())

This opens two QFileDialog windows. Interestingly, one of the windows does not inherit the 'style' of my GUI, set my setStyle, but does return the filepath string. The other QFileDialog does inherit the style, but can not return the filepath string. I have found the QFileDialog documentation helpful, but have not been able to create a QFileDialog box that both produces the filepath string, and inherits the style of my GUI. What mistake am I making?

Was it helpful?

Solution

You actually created 2 windows.

The function QFileDialog.getOpenFileName is static, meaning that it creates its own QFileDialog object, shows the window, waits for the user to select a file and returns the choosen filename.

You should only need that line:

filepath = str(QFileDialog.getOpenFileName())

If you set the style at the application level (with QApplication.setStyle), it might be applied to the window if you use the non-native dialog:

filepath = str(QFileDialog.getOpenFileName(options=QFileDialog.DontUseNativeDialog)))

OTHER TIPS

getOpenFileName is a convenience function that "creates a modal file dialog". That's why you're getting the second dialog.

Use filedialog.exec() to show the dialog and fileDialog.selectedFiles() to get the filename.

exec is a reserved word in python, you must use exec_().

dialog = QFileDialog(self)
dialog.exec_()
for file in dialog.selectedFiles():
    print file
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top