3

I'm building my first plugin and I meet an issue with some variables. I've made some custom fields to store some variables 'project_actitle' dedicated to a project. The plugin uses these variables. The error appears when either I launch Qgis and there is not any project, or when I use a project that doesn't have these customs fields. That logical, because the plugin doesn't find the field 'project_actitle'

project = QgsProject.instance()
title_file = QgsExpressionContextUtils.projectScope(project).variable('project_actitle')

the error:

Traceback (most recent call last):
  File "C:/PROGRA~1/QGIS3~1.10/apps/qgis/./python/plugins\xdr_import_photo\xdr_import_photo.py", line 296, in run
    self.dlg.lineEdit_2.setText(path + folder +  title_file + ".shp")
TypeError: can only concatenate str (not "NoneType") to str

How can I avoid this error? I would like to check if the project own this fields and pass the "variable called" to avoid the error or something like that..

1 Answer 1

3

The problem is you try to concatenate None with a string. So the solution is simple: just check if title_file is None, and set a default string value.

project = QgsProject.instance()
title_file = QgsExpressionContextUtils.projectScope(project).variable('project_actitle')
if title_file is None:
    title_file = "my_default_value"

Depending on whether the title_file variable is used elsewhere, and should be kept as None, you could also change the following line

self.dlg.lineEdit_2.setText(path + folder +  title_file + ".shp")

to

if title_file is None:
    self.dlg.lineEdit_2.setText("")
else:
    self.dlg.lineEdit_2.setText(path + folder +  title_file + ".shp")
1
  • Very complete answer with explanation ! thanks
    – zlikotp
    Dec 24, 2019 at 10:02

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.