Email Verification Library Open-Sourced

I have decided that I will need some reusable code across multiple number of my own PHP based projects. So, it was logical decision to introduce some package, and reuse it. The only decision that I had to make was if it should be open-sourced or not. I have decided that there is nothing secret about it, and it might be really useful for other developers, too. Thus, I have decided to introduce Email Verification Library, and put it not just to GitHub, but also to composer. You can see it here:

  1. https://github.com/vaidotasstrazdas/email-check-api/
  2. https://packagist.org/packages/developernode/email-verify

In other words, I feel that I should add some of my code to open-source community, thus I have introduced the library, and moved to both GitHub and Packagist. Hopefully, developers will like this library.

Builder Design Pattern

Builder is categorized as a Creational Design Pattern. Why is it so? Because it is used to create objects in some way. In what way exactly? This article intends to explain that. If something is unclear to you, please ask it in the comments. The main problem is that there are so many extremely and unnecessarily complex examples that this design pattern (as well as other ones) becomes one of the hard things. However, this should not be so. Builder is pretty easy when you understand what it does.

First of all, we have to know what is the difference between object and class. Object itself is an instance of the class, i.e. some operator (it is called “new” in most of the OOP languages) is able to use a definition of the class (variables, methods), and based on that to assign some space in memory where both data and both instructions are defined. If you want to know more, you should definitely look into Assembly and its’ principles. However, point of this article is to explain Builder.

So, you know pretty basically (understanding can be simple, but in this case it is even correct one) what an object is. So, what is a class? I have already explained that, either. So, to make things clear, I should just repeat the same thing. The class is some definition defining data, data types and methods that an instantiated object will be able to perform. In other words, you can treat a class from a mathematical point of view, i.e. you can treat the class as a set of objects that instantiate from the class defined.

Why do we need to know that? Because Builder itself is also a class, and we should talk about exact definition of the Builder itself. And here we come to even more abstract way of thinking – definition of the class itself. What is it? Well, it is simple. Definition of the class is an interface, and class is the instance of the interface. So, what is the interface for Builder? The most abstract interface for Builder can be written in the following way:

interface IBuilder<T> {
    T build();
}

And that is it. T is some type of the class we want our builder to be able to build.

But why do we need building at all? Can’t we just write everything like that? For instance, we have class called “Customer” with some fields, and we just define everything we need. In that same “Customer”, we define multiple methods setting values, and so on. Actually, we can. And I will show how you can do that. Below is the following code that does exactly that:

class Customer {
    public Field1 { get; set; }
    public Field2 { get; set; }
    public Field3 { get; set; }
    public Field4 { get; set; }
    public Field5 { get; set; }
    public Field6 { get; set; }
    public Field7 { get; set; }
    public Field8 { get; set; }
    public Field9 { get; set; }
    public Field10 { get; set; }
}

How the one would instantiate such a massive class? Well, like this:

var customer = new Customer();
customer.Field1 = "Some value 1";
customer.Field2 = "Some value 2";
customer.Field3 = "Some value 3";
customer.Field4 = "Some value 4";
customer.Field5 = "Some value 5";
customer.Field6 = "Some value 6";
customer.Field8 = "Some value 8";
customer.Field9 = "Some value 9";
customer.Field10 = SHA512(customer.Field8 + customer.Field9);

Oops, we forgot to set Field7. Also, we see that Field10 can be logically deduced from Field8 and Field9, so why are we setting it still here? And what if the algorithm to set the value will change? Well, we are going to rewrite this code all over again. And maybe we will end up in a situation where there is going to be 2-3 places of the same repeating logic. After that, we will invent some method that abstracts all of this logic, and this method basically will be some sort of Builder. So, in any case, even the worst developers that want their code to shine are going to invent Builder itself by themselves. And this is the reason why Builder is a pattern.

So, seeing this use of code we see that Builder is a good Design Pattern for the following purposes:

  1. It allows to abstract data items in the class from the value setting and manipulation methods.
  2. Since Builder is a class, we can use it as an interface somewhere else. Also, we can add multiple dependencies (such as the one as algorithm used in setting the Field10).
  3. Potential API client does not need to worry about internals of setting the class. Client might concentrate just on the data in the class itself and that’s it.
  4. We can guarantee that builder will return the finalized state of the class, i.e. the object that is really correct and integral.

However, there is one “drawback” in the Builder design pattern. By introducing a Builder, you also increase the number of lines of code. However, I would not call it as a drawback. When introducing any of the class, any line of code, you are boosting size of your code base. So, basically the whole programming can be treated as a one big “drawback” if you think that adding more lines to code is a “drawback” by itself.

Finally, how to implement the Builder design pattern? As we saw before, we have an interface for the abstract Builder that is able to build instances of class defined by type T. So, we implement this abstract interface for Customer class:

class CustomerBuilder {
    private var readonly _customer = new Customer();
 
    public Customer build() {
        // Here, we can ensure that _customer will be of finalized state. For instance, we can throw an exception marking that something is not set.
        return _customer;
    }
}

But wait, is that really it? Actually, no. No one is going to use abstract builder interface directly. Most of people are going to instantiate some concrete builder themselves through “new” operator or its’ abstraction called “IoC Containers”. And these concrete builders are going to have pretty solid methods. For instance, we can add the method that sets both Field8 and Field9:

class CustomerBuilder {
    private var readonly _customer = new Customer();
 
    public CustomerBuilder setFields(string field8, string field9) {
        customer.Field8 = field8;
        customer.Field9 = field9;
        customer.Field10 = SHA512(field8 + field9);
 
        return this;
    }
 
    public Customer build() {
        // Here, we can ensure that _customer will be of finalized state. For instance, we can throw an exception marking that something is not set.
        return _customer;
    }
}

There is one important thing. Actually, it is not really important for the Builder design pattern, but it is really comfortable to do so: When adding some setter method, return instance of the Builder itself, so we would be able to chain all of the Builder methods.

And that is it. Builder design pattern implemented. So, when to use it exactly? Basically, use it whenever you feel that you have pretty complex looking class (like 5-10 or more fields), and you might expect that setting values for the fields is going to be painful, and this setting logic can be reused. So, as a general rule, you can make your decision based on answers to these questions:

  1. Does the class have at least five fields? If so, you might want to use Builder.
  2. Can we set values for the class fields based on other field values? If the 1st is yes, and this is yes, then you should definitely use Builder Design Pattern.

Thanks for reading, and I hope that now you really know what is the Builder, how to use it, and when to use it.

How to Crash (Almost) Any Android App Through Autofill Framework

Autofill Framework is one of the things that should have resolved lots of issues regarding password managers or other apps that strive in simplifying the process of filling in the data for the user (https://www.xda-developers.com/android-os-autofill-framework-will-finally-resolve-a-long-standing-lag-issue-with-password-managers/). There were even threats by Google itself that apps who are not going to use Autofill Framework instead of Accessibility Service to fill in the data, are going to be kicked out from the Play Store (https://www.xda-developers.com/google-threatening-removal-accessibility-services-play-store/) . About the latter, I think Google went too far given that Autofill Framework being developed for almost two years still has massive issues, such as being able to kill any other Android app.

This framework is being adopted, but so far Autofill Framework does not cover pretty basic use cases. And there is not just not covering, but through Autofill Framework you can crash other apps. I have even created a ticket for that: https://issuetracker.google.com/u/0/issues/125158212 . In my GitHub repository, you can get the code which demonstrates how to use Autofill Framework to crash other Android apps: https://github.com/vaidotasstrazdas/autofill-crash-demo .

The idea is simple – simulation of dataset being no longer available which might happen due to lots of circumstances. For instance, user logs out, and another user logs in which does not have any data that previous user had. As you can see, use case is really valid, often occuring, but such use case crashes the app you want to autofill. Hopefully, Google will fix this bug, or provide another way to make sure this issue is resolved.

stackoverflow is really a toxic community

Just another article about why stackoverflow sucks. Like these ones: https://www.reddit.com/r/rant/comments/701fgu/stackoverflow_sucks/, https://sergworks.wordpress.com/2012/09/26/why-stackoverflow-sucks/, https://hackernoon.com/the-decline-of-stack-overflow-7cb69faa575d, and so much more. Except here I will point out another negative thing which is regarding post edits. It is pointless to do any edits here in order to improve other people content, because all of your edits will get rejected no matter how valuable they are.

There was a guy who posted a huge boilerplate code I tried to use for my own needs (https://stackoverflow.com/questions/7710357/how-to-make-qscrollbar-with-fixed-size-handle/34352061#34352061), and I have noticed a couple of problems in it – first of all, he extends a Qt class, and does not use Q_OBJECT macro which is necessary for the signal/slot mechanism to work. Then, he made a typo, i.e. instead of QScrollBar, he wrote QScollBar (letter ‘r’ missing). Quite obvious mistakes for the Qt developer, yes? So, I have edited his comment, and pointed out all of the problems. And below you can see what did I get.

According to some dudes that call themselves @il_raffa and @Rick, this edit is pointless, because somehow it is directed to the author, and should have been written as comment. Well, I see no problem in that, but is it worth it to copy the same code, and then note what is wrong in it? It is not, since it would give no actual value for the community. Better value would be given through edited code. Thus, it was exactly directed to the mediocre code which should be fixed at least a bit. Also, it is mentioned these guys have no clue about Qt. The first one is some math or computer science guy, and another one probably has never touched C++ in his life at all, thus talking as him knowing Qt would probably be pointless. And stackoverflow somehow “thinks” that these guys are competent enough to reject or accept edits regarding tool-set they know nothing about. That is stackoverflow for you. This should never really be the case, because a guy knowing nothing about C++/Qt can not even understand the code, so how is he or she supposed to understand if edit is worth anything or not? If edit is simple enough, then maybe, but if it contains some framework-related things, then such people can not understand why I have suggested this as an edit.

In other words, stackoverflow community is really toxic which started as a great idea, but there are now lots of members who just reject and downvote everything they do not like or understand. Is it their fault? I do not think so. If the system for the community developed is good enough, it will not attract toxic people.

new Date() is really new one

I have encountered quite an interesting thing under Java, Also, under Swift, but semantics will go for Java this time.

Does new Date() == new Date()? Well, mostly it would be yes (for the one-liner code at least it would be almost yes!). However, under some circumstances it would not be the case. Read the following (https://docs.oracle.com/javase/7/docs/api/java/util/Date.html): “The class Date represents a specific instant in time, with millisecond precision”. Definitely, it is crystal clear that new Date() represents something for time at any given time. However, this “any given time” is only understandable for Java VM, not for human or some alien. Should it really be this way? Well, in some circumstances I would not think so.

If new Date() !=(sometimes) new Date(), then it should mean that new SomeCustomInterfaceImplementation() !=(somtimes) new SomeCustomInterfaceImplementation(). In other words, you provide no arguments, and you already would get completely undefined behavior. In my opinion, this should not be the case. Why? Because “new” is a keyword, not something that will give you definitely completely different from previous one. Semantically, it may mean that yes, we should treat “new” directly, and object might slightly differ from previous instance. However, there may be lots of thinking, and so on. Still, shouldn’t we be clear about that?

For instance, why do we even bother overriding equals() / hashCode() methods just to make sure that “==” would work in the same way given arguments are completely the same despite any of the circumstances (such as time, and anything like that). In my opinion, time is something that we can’t control, so I think even Java/Swift should not go this way, i.e. trying to give us some real current Date which might be not possible at all even in thousands of years.

Some developers might disagree with me. And I think it is natural. More on that, it would be even greater to hear other developers’ opinion on this matter. But for now, I think that time is another argument for the software that should be specified, since we humans are still not able to tell which time is it exactly given our limitations of our clocks, computers, and so on.

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).