PyQt4 what is the best way to center dialog windows?
Asked Answered
L

2

6

When I .show() an dialog it usually shows up a little to the left, I have no idea why. I wanted to center all my opened dialogs so i used:

qr = dlgNew.frameGeometry()
cp = QtGui.QDesktopWidget().availableGeometry().center()
qr.moveCenter(cp)
dlgNew.move(qr.topLeft())

and also:

sG = QtGui.QApplication.desktop().screenGeometry()
x = (sG.width()-dlgMain.width()) / 2
y = (sG.height()-dlgMain.height()) / 2

dlgMain.move(x,y)
dlgMain.show()

My question is, which is proper/better way to use, and what is the difference?

Latrinalatrine answered 14/9, 2012 at 22:23 Comment(1)
Not sure about this specifically but in general you don't want to use the screen size, because the taskbar takes up a (sometimes large) portion of it.Glassware
C
7

If you don't explicitly specify a position, Qt will let the window manager of the OS decide where to put the window. In your case "a little to the left" is what your window manager decided.

As for the two approaches, there are a few differences.

First, .availableGeometry() vs .screenGeometry(). .screenGeometry() gives you the whole rectangle of the screen. Where as .availableGeometry(), returns the usable rectangle. That is the area where certain permanent components, like Taskbar in Windows, are excluded. (Docs explaining the differences)

Second, .frameGeometry() vs width()/height(). .frameGeometry() returns the total area that the window occupies on the screen. On the other hand, width()/height() returns the width and height inside the window which excludes window frame, title bar, etc. (Docs explaining the differences)

With these in mind, I'd say the first approach is more appropriate.

Carrie answered 14/9, 2012 at 22:53 Comment(0)
C
2

According to the documentation;

A dialog is always a top-level widget, but if it has a parent, its default location is centered on top of the parent's top-level widget (if it is not top-level itself). It will also share the parent's taskbar entry.

I'm not sure if you want to only center your main window on launch but if you want to center your modal dialogs, you can simply make the main window the modal dialog's parent by calling ...

setParent (self, QWidget parent)

or doing so from init

__init__ (self, QWidget parent =YOUR_MAIN_WINDOW_HERE)

Hope that helps!

Cynical answered 22/11, 2016 at 8:45 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.