Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 507
Marko Avatar asked Sep 14 '12 22:09

Marko


People also ask

How to center window PyQt?

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.

What is dialog in pyqt5?

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.


2 Answers

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.

like image 111
Avaris Avatar answered Sep 18 '22 17:09

Avaris


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!

like image 24
Mike JS Choi Avatar answered Sep 19 '22 17:09

Mike JS Choi