Marko
Marko

Reputation: 20513

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?

Upvotes: 6

Views: 6554

Answers (2)

Mike JS Choi
Mike JS Choi

Reputation: 1151

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!

Upvotes: 2

Avaris
Avaris

Reputation: 36715

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.

Upvotes: 7

Related Questions