Monday, 23 December 2019

pyqgis - How to Format QGIS Field names on Editor Form



I am using PostGIS table in QGIS with custom QGISFieldWidgetFactory. However, I wanted to rename the field names in QGIS Edit Form from say first_name to First Name using Python. Currently, I was able to format all labels/field names using the following method.


class WidgetWrapper(QgsEditorWidgetWrapper):
....
def format_form(self):
title = format_name(
self.entity().short_name
)

title = QApplication.translate(
'WidgetWrapper',

'{} Editor'.format(title)
)

# Set title and format labels for QGIS form
if self.parent.parent() is not None:
self.parent.parent().setWindowTitle(title)
label = self.parent.parent().findChildren(QLabel)[-1:]
if len(label) == 1:
text = label[0].text()
formatted_text = format_name(text)

label[0].setText(formatted_text)

....
def initWidget(self, widget):
....
self.format_form()

This is not a clean way and it doesn't work in QGIS 2.8. Also on QGIS 2.14, it can't work for the last field name. More over, it is not good performance wise as format_form() is called for every field in the layer which is not desirable.


Is there a fix for this?



Answer




The proper way to dealing with this is to use an alias.


You can use addAttributeAlias for this (as usual, check the documentation for this)


This way it will not only be used in python-preprocessed forms but also in the attribute table and other places.


No comments:

Post a Comment

arcpy - Changing output name when exporting data driven pages to JPG?

Is there a way to save the output JPG, changing the output file name to the page name, instead of page number? I mean changing the script fo...