Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to anchor pushButton to the widget?

Tags:

c++

qt

I've created very simple window with one button on it. My button id 10 pixels from right edge of the window and 10 from the bottom. I'd like to keep this position even when the window will get resized. That means, still 10 from the right and 10 from the bottom.

How to do this ??

Thanks

zalkap

like image 435
zalkap Avatar asked Sep 09 '10 00:09

zalkap


2 Answers

Install a QGridLayout on the widget with 2 columns and 2 rows, add the button on the bottom-right cell, then set the first row and the first column to stretch.

QWidget *widget = new QWidget(); // The main window
QGridLayout *layout = new QGridLayout(widget); // The layout
QPushButton *button = new QPushButton(QString("Button"), widget); // The button

layout->setContentsMargin(10,10,10,10); // To have 10 pixels margins all around the widget
layout->addWidget(button, 1, 1);
layout->setRowStretch(0, 1);
layout->setColumnStretch(0, 1);
like image 60
Fred Avatar answered Oct 01 '22 01:10

Fred


In general, use a layout. It's the easiest and most robust solution, and it works best with unpredictable widget sizes (and they are unpredictable in most cases, due to different platforms, font sizes, translated strings etc.). If you really need to position something manually (doesn't happen often), you can reimplement resizeEvent() in the parent and move the children yourself. E.g.

void MyParentWidget::resizeEvent( QResizeEvent* ) {
    m_child->move( width() - m_child->width() - 10, height() - m_child->height() - 10 ); 
}

This moves the child to the bottom-right corner.

like image 40
Frank Osterfeld Avatar answered Oct 01 '22 00:10

Frank Osterfeld