Reputation: 586
I have below code to open pyqt5 in secondary display although print
gives secondary screen resolution, but opening in first display where is my fault?
a = QApplication(sys.argv)
w = App()
# screen_count = a.desktop().screenCount()
screen_resolution = a.desktop().screenGeometry(1)
window_width = screen_resolution.width()
window_height = screen_resolution.height()
print(window_width,window_height) # it gives me secondary window res
x = (screen_resolution.width() - window_width) / 2
y = (screen_resolution.height() - window_height) / 2
w.move(x, y)
w.show()
Upvotes: 0
Views: 170
Reputation: 48260
Your computation is wrong: window_width
is equal to screen_resolution.width()
(and the same goes for the height), so x
and y
will always be 0.
Besides, it doesn't consider the origin of the screen, so it's always based on (0, 0)
even if the screen starts from another x or y.
Also, desktop()
is obsolete, and you should use QGuiApplication.screens()
.
Finally, top level widgets have a default size of 640x480 (unless a minimum and/or maximum size has been specified), while you should use their sizeHint()
instead if available (eg. when the widget is a container and has a layout set).
screen_resolution = a.screens()[1].availableGeometry()
window_size = w.sizeHint() or w.size()
window_width = window_size.width()
window_height = window_size.height()
x = screen_resolution.x() + (screen_resolution.width() - window_width) / 2
y = screen_resolution.y() + (screen_resolution.height() - window_height) / 2
w.move(x, y)
w.show()
Using QRect helper functions it's even easier:
geo = QRect(QPoint(), w.sizeHint() or w.size())
geo.moveCenter(a.screens()[1].availableGeometry().center())
w.setGeometry(geo)
w.show()
Upvotes: 2