Search code examples
c++qtpointersqgridlayout

QWidget::layout() can't return QGridLayout?


I have a QWidget that contains a QGridLayout, which in turn contains a handful of QPushButtons. These are all generated programmatically. Later in the code (separate from where the layout is defined), I need to be able to add more pushbuttons to specific row/column positions in the layout.

I tried using: widget->layout()->addWidget(button, row, col) to reference the layout and add the buttons. However, widget->layout() only returns a generic QLayout item, which does not allow me to specify row and column values. Is there any way to reference a QGridLayout from a specific widget, without having to know the layout by name? I'm using Qt 4.8 if it makes a difference.


Solution

  • You can always cast it to QGridLayout* by dynamic_cast:

    auto gridLayout = dynamic_cast<QGridLayout*>(widget->layout());
    

    If you're sure widget->layout() points to your QGridLayout you don't have to check and can use static_cast. Otherwise, check gridLayout against nullptr.