I want to keep a QWidget (or QDialog) centered to its parent widget. Is it really required to connect to signals of the parent widget or is there an easier way (something to
I solved it myself and just to answer my own question if someone will find it helpful.
Keep it in the center:
void MyMainWindow::moveEvent(QMoveEvent* event)
{
const QPoint global = this->mapToGlobal(rect().center());
waitDialog->move(global.x() - waitDialog->width() / 2, global.y() - waitDialog->height() / 2);
}
... where waitDialog
is an instance of my "Wait..." indicator. This needs to override the moveEvent
method of the parent (here MyMainWindow
).
If your QWidget is an in-the-same-window child of its parent, then you could add it to the parent's QLayout (e.g. QBoxLayout or QGridLayout) with the proper settings to have the layout center it.
If it's a QDialog (or some other QWidget that is set to be its own separately-moveable top-level window), then the QLayout approach won't work; what you could do instead is override the parent widget's resizeEvent() method to call setGeometry() on the child dialog, so that the child dialog gets its position and/or size updated whenever the parent gets resized. You might also need to override the moveEvent() method of the parent's top-level-window to detect when the user has moved the parent window, so that you can move the dialog's position to match that movement. I'm not 100% sure this is behavior you would really want though, since normally the user expects to be able to move dialogs about the screen independently of their parent windows.