Visualize Postgres JSON data in QML widgets

As promised some time ago in “The new QML widgets in QGIS – When widgets get unbridled” we still owe you some fancy unicorns, but first let’s have a look at another nice feature that has been introduced in QGIS 3.4 LTR,  the reading of PostgreSQL JSON and JSONB types.

With JSON you have a lot of possibilities for storing unstructured data. In our case, it’s mainly interesting when the data are stored as an array or a JSON object. Let’s have a look at two examples.

Visualize Postgres JSON data with common widgets

With the usual QGIS widgets “List” and “Key/Value” you are able to display JSON arrays and simple JSON objects.

JSON array as List

Simple JSON object as Key/Value

Or of course both as plain text in the “Text Edit” widget:

Say hi to Postgres JSON in QML widget

Probably, your JSON data does not look really nice with the aforementioned widgets, luckily since QGIS 3.4, you are free to create your own QML widget. Since QGIS already loads the JSON data into structures that are supported by QML, we can use all the JSON data within the QML code.

Let’s assume you have the JSON array from above and you like the elegance of the blue of Jacques Majorelle. You create your personal list widget by adding the JSON field as an expression:

You will have your very personal list:

JSON also allows storing more complex data, like for example a list of objects. In that case, you will reach the limits of the common QGIS widgets.

Let’s assume you have a table looking like this:

nomenclatura name link
Apis mellifera mellifera European dark bee
Apis mellifera carnica Carniolan honey bee
Apis mellifera Buckfast bee

In JSON it would be stored like this:

With the QML Widget you can use the QML TableView to visualize:

Or, even more powerful, you can create your super individual table using the model and create each row by using a QML Repeater.

Additionally, you can use a lot of fancy stuff like:

  • mouse interaction
  • animation
  • opening an external link
  • … and so on

The QML code for that looks like this.

And that’s it

I hope you liked reading and you will enjoy using it to make beautiful widgets and forms. If you have questions or inputs, feel free to add a comment.

… and in case you still asking where the promised unicorns are. Here’s is a super-fancy implementation 😉

Posted in GIS, Non-commercial, PostgreSQL, QGIS, QML, Scripts

Leave a Reply

Contact GmbH
Mythenstrasse 37A
8840 Einsiedeln

Twitter: @OPENGISch
Mobile: +41 (0)79 467 24 70
Skype: mbernasocchi
Support QField development
%d bloggers like this: