PyQGIS – Fix QFileDialog.getSaveFileName() Error in QGIS Plugin Code

oserrorpyqgisqgis-plugins

I'm working with Plugins Builder to create a simple plugin with QGIS3 "SaveAttributes", I'm following the official tutorial on QGIS Tutorials.

I'm installed Python 3 and Python 2 is already installed with ArcGIS, I have installed also the PyQt5 and Qt Creator. (I give details because I think that the error was not provided by the code)

The error I got:

TypeError: setText(self, str): argument 1 has unexpected type 'tuple'
Traceback (most recent call last):
File "C:/Users/REDA DRISSI/AppData/Roaming/QGIS/QGIS3\profiles\default/python/plugins\reda\module.py", line 190, in select_output_file
self.dlg.lineEdit.setText(filename)
TypeError: setText(self, str): argument 1 has unexpected type 'tuple'

For this code:

def select_output_file(self):
    filename = QFileDialog.getSaveFileName(self.dlg, "Select output file ","", '*.txt')
    self.dlg.lineEdit.setText(filename)

I tried to use str() function :

self.dlg.lineEdit.setText(str(filename))

Gives this Error:

OSError: [Errno 22] Invalid argument: "('C:/Users/REDA DRISSI/Desktop/DATA/finaldd/reda.txt', '*.txt')"

I think the problem is related to the default version of Python used by windows and QVariant, but I don't know how to resolve the problem.

Best Answer

Try

self.dlg.lineEdit.setText(filename[0])

instead of

self.dlg.lineEdit.setText(filename)