Check boxes affect margins of grid layout on MAC

A couple of days ago, I have encountered quite a strange bug. When working and organizing layouts for elements in different parts of the system, our QA reported that somehow texts are not aligned properly, and this happens on MAC only. At first, I have thought that I have made a typo in setting content margins. However, I have found out that margins were perfectly identical, thus this was not a problem. Then, for some reason, I have decided to remove checkbox from a grid layout. And what happened? Layout started to behave as perfectly aligned.

After observing this behavior, I have decided to create experimental Qt project, and see the behavior of check boxes in the grid layout, so I would be able to properly report a bug to Qt’s bug tracker if this is really a Qt issue. After doing so, I have observed that this is really a Qt issue. The behavior was the following:

  1. On Windows, everything worked exactly as expected, i.e. layout margins were not changed.
  2. On MAC, for some reason the margins were changed, and I am not sure why.

Final Thoughts

This Qt behavior is a bit annoying, because you expect that elements in the layout would not affect the layout which is in higher level of hierarchy. However, for this issue, the workaround exists. You just need to put checkbox to a separate layout, and the parent layout won’t be affected (but the containing layout will).

The following link is exact bug report: https://bugreports.qt.io/browse/QTBUG-62617

Proper way to clean QLayout

This is the final part of post series about cleaning QLayout in Qt. In the first part (http://developernode.net/2017/05/20/clean-qlayout-properly-part-one/), I have introduced two ways to clear QLayout. In the second part (http://developernode.net/2017/05/21/clean-qlayout-properly-part-two/), I have shown why these ways are wrong. In summary, the first way just removes QLayoutItem instances, and the second way fails on custom signals handling. So, in this post I will show the way how to delete QLayout properly, and will discuss why this way is the correct way to do so.

Widget must be removed when control returns to the event loop

In the second part, we found out that app crash is caused that delete is called without taking into account such a fact that control must return to the event loop. When control is not in the event loop, it means some event is being handled, and we might face that event handling might be some slot handling the signal. If this is the case, we get app to crash. In other words, we must take care of event loop. So, instead of line delete item->widget();, we should use item->widget()->deleteLater(). Then, according to http://doc.qt.io/qt-5/qobject.html#deleteLater, the object will be deleted when control returns to the event loop.

So, after changing one line, we get the desired result, and no segmentation faults. The code to clear QLayout is the following now:

#include <QLayout>
#include <QLayoutItem>
#include <QWidget>
 
#include "LayoutManagement.h"
 
namespace LayoutManagement
{
    void ClearLayout(QLayout&amp; layout)
    {
        QLayoutItem *item;
        while((item = layout.takeAt(0)))
        {
            // If item is layout itself, we should clear that layout as well.
            if (item->layout())
            {
                ClearLayout(*item->layout());
 
                // After clearing layout, we delete it.
                delete item->layout();
            }
 
            // We check if item has some widget. If so, we also delete that widget.
            if (item->widget())
                item->widget()->deleteLater();
            // Finally, we remove item itself.
            delete item;
        }
    }
}

It turns out to be one small fix to make sure layout is cleared properly. So, reader might ask why do we need three articles to cover such change? That is because no one properly in discussed a way to clear QLayout completely. And also the strange thing here is that Qt documentation itself does not cover such use case which might be very frequent for any Qt developer. And finally, this solution is not complete yet. Yes, after this change app will never crash, but we still have one problem.

Official Illusion of Clearing QLayout

Do you remember the official way of clearing QLayout discussed in the second part? And now we use deleteLater() to clear layout. And from Qt documentation we saw that layout will be cleared when control will return to the event loop. What does it mean? This means that we can create garbled text effect while control did not return to the event loop yet. Mostly, it won’t be a problem, because returning to the event loop will happen fast enough that garbled text effect will not be noticed. However, sometimes heavy loads/reloads might happen (especially, when hundreds of custom widget instances with deep hierarchies are involved). And his might be the case when UI looks very bad for some period of time. And this needs to be solved. But how?

Well, we know exactly that deleteLater() will definitely remove the widget properly. So, the code is correct and complete from this point of view. So, what could we do? Actually, one of ways to solve such problem could be just hiding all the widgets before their removal. In this way, widgets would not be visible, and layout would not look garbled or anything like that event if the widgets are not removed yet.

The code below shows complete solution for clearing QLayout:

// LayoutManagement.h
#pragma once
 
class QLayout;
 
namespace LayoutManagement
{
    void HideAllWidgets(QLayout&amp; layout);
 
    void ClearLayout(QLayout&amp; layout);
}
 
// LayoutManagement.cpp
#include <QLayout>
#include <QLayoutItem>
#include <QWidget>
 
#include "LayoutManagement.h"
 
namespace LayoutManagement
{
    void HideAllWidgets(QLayout&amp; layout)
    {
        for (int i = 0; i < layout.count(); i++) {
            auto item = layout.itemAt(i);
            if (item->layout())
                HideAllWidgets(*item->layout());
 
            if (item->widget())
                item->widget()->hide();
        }
    }
 
    void ClearLayout(QLayout&amp; layout)
    {
        HideAllWidgets(layout);
 
        QLayoutItem* item;
        while((item = layout.takeAt(0)))
        {
            // If item is layout itself, we should clear that layout as well.
            if (item->layout())
            {
                ClearLayout(*item->layout());
 
                // After clearing layout, we delete it.
                delete item->layout();
            }
 
            // We check if item has some widget. If so, we also delete that widget.
            if (item->widget())
                item->widget()->deleteLater();
 
            // Finally, we remove item itself.
            delete item;
        }
    }
}

Final Thoughts

In the series, I have shown a way to clear QLayout in a correct and complete manner without any risk of segmentation fault. Also, this way makes sure all the widgets will be removed with all QLayoutItem instances. Finally, I have shown that, before removal, we should make sure that widgets would not be visible for the actual user, since for a short period of time user might see Qt implementation details, i.e. behavior when not being returned to the event loop.

Cleaning QLayout (Part Two)

In a previous part (http://developernode.net/2017/05/20/clean-qlayout-properly-part-one/), I have summarized two ways to clear QLayout. These were: “official way” (the one that is described in Qt documentation), and SO way that was proposed by Wes Hardaker. In this post, I intend to do the following:

  1. Define clearing QLayout operation rigorously.
  2. Show why both solutions do not work as expected.

 

Definition of Clearing QLayout

From the first sight, it might look that it is irrelevant to define something simple as removing operation from a specific object. However, this needs to be done properly, since Qt documentation says us that by deleting each instance of QLayoutItem we would remove all items from a QLayout. However, we see nothing like that. And the reason for that is Qt documentation uses different definition for delete operation. So, I must emphasize MY definition of delete from some object.

My definition of delete is the following (in my humble opinion, this definition of delete is for the most of developers the same): When deleted from some container, this container must have no elements in it both visually and both in memory. In QLayout case, this would mean that memory would be freed from the items in it after delete. And also, none of the items would be visible in this layout. So, in order to clear QLayout, we must ensure the following:

  1. Memory must be cleared from items in QLayout.
  2. No items can be visible in QLayout.

Later on, we will see how these insurances are made using both of the two solutions presented in the first blog post

Official Way of Clearing QLayout

Let’s say we have such structure of layout. Layout we would like to clear is vertical layout. This layout consists of two QLabel elements, and one horizontal layout having two QLabel elements, either.

Example structure for layout

Knowing everything we want to achieve, I can start writing some code for clearing our QLayout. Let’s say the header (LayoutManagement.h) for this problem would be this:

#pragma once
class QLayout;
 
namespace LayoutManagement
{
    void ClearLayout(QLayout&amp; layout);
}

Then, implementation of the official way to clear QLayout (LayoutManagement.cpp) would look like this:

#include <QLayout>
#include <QLayoutItem>
 
#include "LayoutManagement.h"
 
namespace LayoutManagement
{
    void ClearLayout(QLayout&amp; layout)
    {
        QLayoutItem* child;
        while ((child = layout.takeAt(0)) != 0)
            delete child;
    }
}

Result of this layout cleanup algorithm would look like this:

Qt documentation way of clearing layout (garbled widgets)

The result we get is widgets garbled on each other. Why is that so? Well, as Qt documentation suggests, this way of layout cleanup just means removing layout items, i.e. instances of QLayoutItem. Documentation says nothing about QWidget instances. So, from what we see, we can assume this solution is not a proper way to clear Qt layout.

Almost Proper Way

Code for this way could be implemented like this:

#include <QLayout>
#include <QLayoutItem>
#include <QWidget>
 
#include "LayoutManagement.h"
 
namespace LayoutManagement
{
    void ClearLayout(QLayout&amp; layout)
    {
        QLayoutItem *item;
        while((item = layout.takeAt(0)))
        {
            // If item is layout itself, we should clear that layout as well.
            if (item-&gt;layout())
            {
                ClearLayout(*item-&gt;layout());
 
                // After clearing layout, we delete it.
                delete item-&gt;layout();
            }
 
            // We check if item has some widget. If so, we also delete that widget.
            if (item-&gt;widget())
                delete item-&gt;widget();
 
            // Finally, we remove item itself.
            delete item;
        }
    }
}

And this way looks almost well enough. However, in this way it’s not that hard to make app to crash. Lets say we have a vertical layout having custom label which can emit Clicked() signals on mouse release event. Such label can be implemented in the following way:

// CustomLabel.h
#pragma once
 
#include <QLabel>
 
class CustomLabel
    : public QLabel
{
    Q_OBJECT
    public:
        CustomLabel(QWidget* parent = nullptr);
        virtual ~CustomLabel();
 
    signals:
        void Clicked();
 
    protected:
        virtual void mouseReleaseEvent(QMouseEvent* event) override;
};
 
// CustomLabel.cpp
#include <QVariant>
 
#include "CustomLabel.h"
 
CustomLabel::CustomLabel(QWidget* parent)
{
}
 
CustomLabel::~CustomLabel()
{
}
 
void CustomLabel::mouseReleaseEvent(QMouseEvent* event)
{
    // Emit clicked signal.
    emit Clicked();
 
    // After emiting the signal, I set specific property for the label (this line will make app to crash using the following solution)
    this->setProperty("clicked", true);
}

Now we can promote to this label some of our widgets, and, using this label in such a way that, when label is clicked, the layout would be cleared, we would cause app to crash. Example usage of such a label would be the following:

connect(ui->customLabel, &CustomLabel::Clicked, this, [this]
{
    LayoutManagement::ClearLayout(*ui->verticalLayout);
});

When doing like this, we make sure that after sending Clicked() signal, we would go to the event loop, and in that loop call LayoutManagement::ClearLayout(*ui->verticalLayout); would be handled, since this call is part of the slot which handles CustomLabel::Clicked signal. However, clearing layout, using the solution I have found out on SO, completely deletes CustomLabel instance. But we did not return from the event loop which also means that scope of CustomLabel::mouseReleaseEvent(QMouseEvent* event) is still ACTIVE!!! So, we have a scope to which control is being returned from the event loop. In other words, emit Clicked(); is handled, and now after this call, call this->setProperty(“clicked”, true); is being made. However, the instance is already removed, since we cleared layout in this way. And this means we have an app crash here. Instance of the CustomLabel is destroyed, so trying to execute call this->setProperty(“clicked”, true); causes segmentation fault which also means that app crashes. So, we see that the way I have found on stackoverflow is not complete, since this way does not allow the widget instance to clear layout itself when custom signal handling is complete.

Summary

I have taken a look into two ways of clearing QLayout. The first way was using documentation approach, another one was more complete, but proved not good enough, since it is possible to make application to crash when widget being in a layout emits such a custom signal that handler of it clears layout itself.

Cleaning QLayout (Part One)

One time I was interested in a way to clean up QLayout, since I had a task to make sure some items are reloaded at some point of software execution. Then, I came up across SO page: http://stackoverflow.com/questions/4857188/clearing-a-layout-in-qt . There were various suggestions of clearing a layout in Qt. I was using one of them for a reasonable period of time. However, this proved to be a huge mistake. And I will show you why.

In the series of these posts, I am going to take a look into existing suggestions to clear QLayout. Then, I will take a look into each suggestion, and will show the problem behind each of them. Finally, I will provide you completely proper way to clear QLayout. I would even encourage you to use this solution in your production-level code, since it is completely tested, verified and proved to be stable for a long period of time.

In this post, I am going to take a look into existing suggestions to clear QLayout. There are a couple of them. The first one is an “official solution” to this problem, i.e. described in Qt documentation itself. According to http://doc.qt.io/qt-5/qlayout.html:

The following code fragment shows a safe way to remove all items from a layout:

QLayoutItem *child;
while ((child = layout->takeAt(0)) != 0) {
    ...
    delete child;
}

Basically, the solution is just to delete QLayoutItem, and everything would look fine. However, this solution is wrong, since it does not remove widgets from a layout. So, from this solution we can assume Qt treats differently removing items, widgets, and other objects. Well, in our case clearing layout means completely deleting everything that can be treated as layout level item (in another part, I will take a look into more rigorous definition).

Another solution to clear layout is the one I came across on SO: http://stackoverflow.com/a/4857631/1027730. According to this solution, the following code fragment is good enough to clear QLayout:

void clearLayout(QLayout *layout)
    QLayoutItem *item;
    while((item = layout->takeAt(0))) {
        if (item->layout()) {
            clearLayout(item->layout());
            delete item->layout();
        }
        if (item->widget()) {
            delete item->widget();
        }
        delete item;
    }
}

I must confess that I was using this variation of code myself. This solution is good enough, since it also takes into account the possible fact that layout might have not just widgets, layout items, but widgets in it, then widget in it might have some layouts of it, and so on. So, this code basically makes sure that layout becomes completely empty. However, the biggest problem with this solution is delete item->widget(); code line. Why? Because widgets can send signals, and it is possible that deleting happens when widget’s signals are handled while not being returned from the event loop. And when such a thing happens, we might experience application crash.

In summary, we have these two solutions. And the last solution looks to be taking into account all the clearing logic. However, it is still not complete enough, since it does not take into account event loop being in place (which takes central role in Qt as framework in itself).