Reputation: 78
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
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
Reputation: 8410
Your code seems to be a good attempt to achieve the desired behavior. Two suggestions:
Hope that helps.
Upvotes: 4