Search code examples
qttoolbardockqdockwidgetqgridlayout

QDockWidget with a QGridLayout - Widget within the Layout do not align to the top


I'm attempting to create a dockable toolbar (similar to what you use in Photoshop) that will hold a 2 x (n) grid of buttons. My idea is to use a QGridLayout parented to a blank QWidget, which is added to a QDockWidget, and add buttons to the QGridLayout. This seems to be working except for the aligning.

I've set the align for the buttons...

myLayout->addWidget(button1,0,0,1,1,Qt::AlignTop);
myLayout->addWidget(button2,0,1,1,1,Qt::AlignTop);
myLayout->addWidget(button3,1,0,1,1,Qt::AlignTop);
myLayout->addWidget(button4,1,1,1,1,Qt::AlignTop);

...however the grid is expanding to the full height of the QDockWidget, as seen below: enter image description here

The buttons are also expanding horizontally as well, to fill the entire space. I figure I can just restrict the ability to re-size it horizontally (if this is possible?).

Is there a function I'm overlooking in the doc to control the GridLayout a little better to restrict it filling the entire width/height of the parent widget? And as a side-question, is there a way to prevent a QDOckWidget from being re-sized a certain direction?


Solution

  • Use a QVBoxLayout where you add first your QGridLayout and then add a stretch like this:

    my_vboxlayout->addLayout( my_gridlayout );
    my_vboxlayout->addStretch( 1 );
    

    Alternatively you can tell your QGridLayout that the last row should expand to a maximum size, which will push up the buttons.
    In your case it would be:

    mygridlayout->setRowStretch( 2, 1 ); // give 3rd row maximum space
    

    Links to documentation:
    QBoxLayout
    QGridLayout