How to keep a QWidget (or QDialog) centered to its parent widget?

后端 未结 2 1080
醉酒成梦
醉酒成梦 2021-01-14 15:50

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

2条回答
  •  情话喂你
    2021-01-14 16:41

    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.

提交回复
热议问题