qt4python-2.7pyqt4window-position

PyQt4 what is the best way to center dialog windows?


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?


Solution

  • 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.