Tourman
Tourman

Reputation: 78

Center Qt child windows relative to parent

I have a QMainWindow, which creates multiple QDialog child windows and sets itself as their parent. When there is a single monitor, everything is OK and windows are centered correctly in the current monitor. But when I have multiple monitors, child windows tend to open on the primary monitor, and not on the monitor where the QMainWindow currently resides.

Note that my windows must be able to navigate outside of its parent (they each have the Qt.Window flag set).

So, how do I center a widget, relative to it's parent position (i.e. centered on the QMainWindow) to avoid them opening up somewhere else?

Here is what I currently use to center my windows:

def centerOnScreen(widget):
    desktopWidget = QApplication.desktop()
    screenRect = desktopWidget.availableGeometry(widget)
    widget.move(screenRect.center() - widget.rect().center())

Upvotes: 4

Views: 3288

Answers (2)

Chenna V
Chenna V

Reputation: 10523

To Quote Qt's documentation "The desktop may be composed of multiple screens, so it would be incorrect, for example, to attempt to center some widget in the desktop's geometry."

So as you can see Qt itself says that this is an incorrect way to center a widget.

As @kroonwijk recommended I'd say either use your QMainWindow's geometry() for centering.

In case if you can't get your mainwindow's access in this widget's scope, one way to get top level widgets is using QApplication::topLevelWidgets. Then you can use some tricks (such as meta information) to obtain your mainwindow.

Upvotes: 3

kroonwijk
kroonwijk

Reputation: 8410

Your code seems to be a good attempt to achieve the desired behavior. Two suggestions:

  1. Instead of taking the desktop parameters, try to directly find the left, top, width and height of your QMainWindow.
  2. Use this geometric information to move (and potentially size) your dialog to the center of your application, before calling the Exec method.

Hope that helps.

Upvotes: 4

Related Questions