When loading a PyQt5 Dialog Widget with saved position coordinates, a form will sometimes load off-screen, such as when a user saves the dialog position on a computer with 3 monitors then opens it again on a different device with only one monitor.
QDesktopWidget().availableGeometry()
object gives me the dimentions of a single screen - for example (0, 0, 1920, 1040) - even though I have three screens.
form.geometry()
returns the current position relative to the primary screen and its dimentions. In my example, the primary screen is the center screen and the form is at (2395, 184, 210, 200). If I save these values, the placement will be off screen when I load the form from my laptop.
How do I determine if the current device can display the widget at the saved values?
EDIT - ADDITIONAL REMARKS:
I have looked at height()
and width()
properties as well as screenCount()
and primaryScreen()
properties that will give additional info, but I have yet to discover a property that will tell me whether an x/y point will actually display on an active screen. Will I perhaps need to resort to using a Windows api to get rect values?
Thanks to a hint in the right direction from @ekhumoro, I found the following works (INCORRECT! SEE REVISION BELOW.):
# Get the screen real estate available to the form
ag = QDesktopWidget().availableGeometry(form)
# If the saved values fall within that real estate, we can
# safely assign the values to the form's geometry
if ag.contains(QRect(x_pos, y_pos, h_dim, v_dim)):
form.setGeometry(x_pos, y_pos, h_dim, v_dim)
else:
# Otherwise, set it to default values that ARE available
form.setGeometry(ag.x(), ag.y(), h_dim, v_dim)
The QDesktopWidget object is the same as the QApplication.desktop() object and derives from PyQt5.QtWidgets. QRect is imported from PyQt5.QtCore
REVISION: It is necessary to first set the form's geometry to the saved values and then see if it falls within the available geometry. Checking first, as above, will fail every time if the form was saved anywhere but the primary screen.
# Set the form to the saved position
form.setGeometry(x_pos, y_pos, h_dim, v_dim)
# Get the screen real estate available to the form
ag = QDesktopWidget().availableGeometry(form)
# If the saved values have placed the form within
# that real estate, we can leave it alone.
if not ag.contains(QRect(x_pos, y_pos, h_dim, v_dim)):
# Otherwise, set it to default values that ARE available
form.setGeometry(ag.x(), ag.y(), h_dim, v_dim)
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