Visual QML debugging
Today we are addressing an issue that is always a little tricky, even for experienced QML programmers: how do I know where my on-screen Items are?
Rectangles, rectangles, rectangles!
When we write code that deals with visual objects that change position or opacity, we need to know where these objects are and what their dimensions are. In these cases, a debugging technique that is very simple, but more effective than printing the position of the various objects on the console, is to insert a coloured rectangle inside the object to be displayed and voila! We obtain a nice coloured spot that shows us the position of our object.
In the event that the spot does not appear, we can check a number of aspects:
- we can check that the rectangle has anchors.fill: parent without other dimensions set, thereby avoiding a situation where the debugging tool is the bug itself;
- we can check that the object is visible on the screen. If the opacity is 0 or the visibility is false we will never see the child rectangle, or if the object starts off the screen we will never see it until it enters into view;
- we can check that the object has sensible dimensions: this is commonly the problem and in fact, it is easy to forget to set the dimensions of the objects.
It is also possible to set the opacity of the rectangle to less than 1 if it is necessary to check the relative positions of several components.
If our application was developed with Qt Widgets or with QtQuick (but only starting from Qt 5.2), we can take use GammaRay, a software that that is used to analyse the structure of the program in depth. Here are certain aspects we can display:
- objects instantiated by the application and the parent-child relationships that exist between those objects;
- all objects in a QtQuick scene;
- state machines based on the state machine framework in a view similar to the UML;
- all models created from QAbstractItemModel;
- all the properties of each QObject are also used to change the assumed values on the fly.
GammaRay works with both QtWidgets and QtQuick applications, it’s an open source application and can be downloaded from GitHub.
Performance and drawing
The last resource to analyse the layout of objects and the performance of the application is the QSG_VISUALIZE environment variable. Setting this variable it is possible to view various aspects related to the QML renderer. The most useful setting when we don’t know where the items are, is
QSG_VISUALIZE = overdraw
In this screenshot, we see the blue lines that represent the QML view, while the various layers are represented in green or red. This rendering takes place automatically above the GUI and is used to ascertain whether there are items out of sight, if there are any overlapped items and so on.