Creates a class inherited from QDialog in one of its implementation methods creates a QPushButton * push= new QPushButton(this); button QPushButton * push= new QPushButton(this); I want to make it so that it is in the center of the parent widget. By default, the button is created in the upper left corner and has x and y which are zero.

How to make the setGeometry button so that the button is in the center of the parent widget? and then the pens are not set correctly.

  • one
    From the half width (height) of the parent subtract half the width (height) of the child? Well, to respond to resize, of course. - free_ze
  • To be completely correct, you can make a custom layout manager - inherit from QLayout ( example ) - free_ze

2 answers 2

The easiest thing to do

Picture

This can be achieved in this way:

  Window(QWidget *parent = 0): QWidget(parent) { QHBoxLayout *hLayout = new QHBoxLayout; hLayout->addStretch(); hLayout->addWidget(new QPushButton); hLayout->addStretch(); QVBoxLayout *vLayout = new QVBoxLayout; vLayout->addStretch(); vLayout->addLayout(hLayout); vLayout->addStretch(); setLayout(vLayout); } 

You can do the same with QGridLayout , but it doesn’t have an addStretch method, so you’ll have to write something like

 gLayout->addItem(new QSpacerItem(40, 20, QSizePolicy::Expanding, QSizePolicy::Minimum);, 1, 0, 1, 1); 
  • And if in this window there is already a widget. It is necessary on top of this widget that is already in the window to display a button. - Disastricks Sep.
  • Widget on top of another widget will not be placed by standard layout. But I, frankly, can not imagine why it is needed. - yrHeTaTeJlb
  • We have a form, in it a table for almost the entire widget, if the table is long filled, the window freezes. Before the window hangs up, I want to display a window with a message; the messageBox type message is loading the data, and as the widget expands, that is, it will download all the data it disappears. To do this, I create a button with the text inside, if we have the widget loaded for more than a second, then I go into the condition for 1 msec with the output of the button through QApplication :: processEvent (), and as the widget the button is loaded, it is explicitly deleted. - Disastricks
  • And why the button can not be in the dialog box? - yrHeTaTeJlb

Did so.

 QRect geometry = this->geometry(); int x = geometry.width() - width() / 1.5; 

since it originates from the beginning of another form and it is long, I need its middle.

int y = screenGeometry.height() - height / 2;

Next, install the button

push->setGeometry(x,y,282,50);