Search code examples
c++qtc++11qt4qt5

qobject_cast<QVBoxLayout*>(layout()), is the appropriate cast?


Considering the layout was set in a QWidget with the following code:

setLayout(new QVBoxLayout);

And then it needs to be retrieved (to add more stuff to the layout). This was done with the following code:

QHBoxLayout *hLayoutTime(new QHBoxLayout);
qobject_cast<QVBoxLayout*>(layout())->addLayout(hLayoutTime);

qobject_cast is the appropriate kind of cast to use here?


Solution

  • To avoid unneded casting write this like this:

    void YourWidget::setupContents()
    {
         QVBoxLayout *vLayout = new QVBoxLayout(this); // effectively this does setLayout(new QVBoxLayout);
    
         QHBoxLayout *hLayoutTime(new QHBoxLayout);
         vLayout->addLayout(hLayoutTime);
         … … …
    }