PDA

View Full Version : Pyqt: How to show a QFileDialog?



robgeek
9th October 2016, 15:24
Hi!

I would like to choose a path for a file that will be downloaded from internet. To do that I tried to create a button, when pressed will open a QFileDialog so I can choose the path. To make my initial GUI i'm using Qt Designer 5.7 and pyqt5.

The output when i hit "Folder" button:

Traceback (most recent call last):
File "teste.py", line 49, in destination
self.folderPath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select folder');
TypeError: getExistingDirectory(parent: QWidget = None, caption: str = '', directory: str = '', options: Union[QFileDialog.Options, QFileDialog.Option] = QFileDialog.ShowDirsOnly): argument 1 has unexpected type 'Ui_MainWindow'
Aborted (core dumped)



from PyQt5 import QtCore, QtGui, QtWidgets
#...
self.destinoButton.clicked.connect(self.destinatio n)
#...
def destination( self ):
self.folderPath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select folder');


How can I fix it?

anda_skoa
9th October 2016, 17:46
Well, as Python told you, the first argument of getExistingDirectory() is not what it expects.

You pass an object of type "Ui_MainWindow" and it expects a QWidget.

Did you derive from the designer generated class instead of using it?

Cheers,
_

robgeek
10th October 2016, 01:51
Here my class definition:

from PyQt5 import QtCore, QtGui, QtWidgets

class Ui_MainWindow(object):
def setupUi(self, MainWindow):
#...
self.destinoButton.clicked.connect(self.destinatio n)
#...
def destination( self ): #Now instead of "self" is "MainWindow".
self.folderPath = QtWidgets.QFileDialog.getExistingDirectory(self, 'Select folder');

I changed "self" to "MainWindow" and is working fine. I have no idea why, by is working. I'm newbie in Python.

anda_skoa
10th October 2016, 08:35
This looks like you are changing the code that has been generated from the designer's output instead of just using that code inside MainWindow.

Which is usually a very bad idea as this means you can no longer use designer for that form, i.e. can't add/change/remove anything with designer, as the next code generation step would then overwrite all your manual code changes.

I recommend considering to use this properly.

Cheers,
_