Search code examples
c++qtqwidgetqlayout

Convert between QLayout and QWidget


I have two examples where I'm basically creating wrapper objects rather than what would ideally be a simple conversion.

If foo is a QWidget* instantiated earlier, can I avoid creating a wrapper QLayout for it:

const auto layout = new QVBoxLayout();
layout->addWidget( foo );
const auto frame = new QLabel( QLatin1String( "Why Do I Need a Layout?" ) );
frame->setLayout( layout );

If foo is a QLayout* instantiated earlier, can I avoid creating a wrapper QWidget for it:

const auto widget = new QWidget();
widget->setLayout( foo );
const auto tabs = new QTabWidget();
tabs->addTab( widget, QLatin1String( "Why Do I Need a Widget?" ) );

Solution

  • Widget doesn't have to have a layout. You can add child widgets to a widget by setting the widget as their parent. But then you will have to adjust the size and position of the child widgets manually.