Search code examples
c++qtqt5qwidgetqlabel

qt minimumSize() returns 0 but in qt designer it is set to non-zero


There's a custom widget inherited from QLabel which is promoted for an advanced functionality. Its minimumSize (for width and height) is set to 150 in qt designer.

But the calls to minimumSize.width(), minimumSize().height() in the constructor of the custom widget returns 0 for some reason

InventoryItem::InventoryItem(QWidget* parent): QLabel(parent)
{
    qDebug() << minimumSize().width(); // 0 ???
    qDebug() << minimumSize().height(); // 0 ???
}

However, from the mainwindow constructor it returns correct values (150, 150) by calling ui->thatWidget->minimumSize().width(); // 150, ... and same for height

Also there are vertical and horizontal layouts of the widgets on the mainwindow.

I'm just not that familiar with GUI programming in QT.

What's happening there ??

How to get correct values from the custom widget ??


Solution

  • The constructor of the main window starts with the following line: ui->setup(this);. This is a call to the setup() function of the moc file automatically generated for the main window. This function constructs the InventoryItem and THEN sets its minimum size. Seeing is believing, so take a look at the moc file in the folder where the project is built. So by calling ui->thatWidget->minimumSize().width(); later on in the constructor of the main window the expected minimum width of 150 is reported. At the time of the construction of InventoryItem however, the minimum size is not yet set, hence calling qDebug() << minimumSize().width(); in its constructor reports the default value of the minimum width. The documentation for QWidget states for the minimum size:

    By default, this property contains a size with zero width and height.

    In short, the world still functions, i.e. the behavior you observe is the expected one.