1

In Attribute Table, there is a form view instead of the table view and the label of listing on the left side can be customized using preview expression. So the user will notice a friendly and meaningful listing. I can customize it manually but I'm creating an automation plugin to load and configure from my datasets.

I observed, it gets stored as <previewExpression> of the layer in the .qgs file. However I don't see any related methods in QgsVectorLayer python class.

How can I customize the preview expression in Python?

Preview Expression

1 Answer 1

1

You may use the setDisplayExpression() method from the QgsVectorLayer() class.

This method only requires a string (remember to escape the ' or the " symbols, otherwise it won't work):

layer=iface.activeLayer()

expression=' \'your expression\' '
layer.setDisplayExpression(expression)

Using an example and assuming you want to set the values of the "numbers" field as a preview expression:

enter image description here

you may use this code:

layer=iface.activeLayer()

expression=' \"numbers\" '
layer.setDisplayExpression(expression)

and you will have this result:

enter image description here

2
  • Hey, that time I really looking for an answer. After a week, I just realize you already answered. I just tested it and you are right. Now I don't have to manually set it every time my script create a new layer... I wonder why I overlook the setDisplayExpression in the dir(QgsVectorLayer). Great, thanks.
    – CallMeLaNN
    Mar 21, 2017 at 16:31
  • 1
    @CallMeLaNN You're welcome. P.S. The overlooking of some crucial method when browsing a class is a common issue for me too! =)
    – mgri
    Mar 21, 2017 at 16:35

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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