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?
To center a Python PyQt window (put it in the center of the screen), we need to do a bit of trickery: we need to get the window properties, center point and move it ourself. At the start of the program, it will be in the center of the screen.
Dialogs are useful GUI components that allow you to communicate with the user (hence the name dialog). They are commonly used for file Open/Save, settings, preferences, or for functions that do not fit into the main UI of the application.
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.
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With