TransWikia.com

QFileDialog.getSaveFileName() error in Plugin code for QGIS

Geographic Information Systems Asked by REDA DRISSI on October 6, 2020

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/QGIS3profilesdefault/python/pluginsredamodule.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.

2 Answers

Try

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

instead of

self.dlg.lineEdit.setText(filename)

Hope this answers your question.

Correct answer by Asad Abbas on October 6, 2020

QGIS 2 and QGIS 3 use PyQt4 and PyQt5, respectively. In PyQt4, QFileDialog.getSaveFileName() method returns filename string like "c:/path/to/file.txt". In PyQt5, that method returns a tuple contains file path and filter string like ("c:/path/to/file.txt", "*.txt"). So to get filename, you should use filename[0] in setText() method:

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

Or, because getSaveFileName() method returns a tuple with two elements, you can use related line as @Matthias states in comments:

def select_output_file(self):
    filename, filter_string = QFileDialog.getSaveFileName(self.dlg, "Select output file ","", '*.txt')
    self.dlg.lineEdit.setText(filename) # without [0]

Strangely, Qt Documentation doesn't state that.

Answered by Kadir Şahbaz on October 6, 2020

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP