Search code examples
pythonpython-3.xpyqtpyqt6

Define monitor for PyQt6 application


I'm wondering how to explicitly define the monitor for the application to start on.
The application yields:

qt.qpa.window: Window position QRect(468,-22 504x896)
outside any known screen, using primary screen

Upon execution.
The MainWindow object is loosely defined as below:

import sys
from PyQt6.QtWidgets import QMainWindow, QApplication


class MainWindow(QMainWindow):

    def center(self):
        """
        Center window in middle of screen 2
        """

        qr = self.frameGeometry()
        cp = self.screen().availableGeometry().center()

        qr.moveCenter(cp)
        self.move(qr.topLeft())

    def __init__(self) -> None:
        super().__init__()

        self.center()
        self.show()


def main():
    app = QApplication(sys.argv)

    # Init window
    window = MainWindow()
    sys.exit(app.exec())

I'm on a Mac laptop where i have multiple virtual desktops, which are assumed by PyQt6 to be physical monitors.

How do I explicitly set the application to open on the primary / 1st monitor?


Solution

  • Can you try something like below. (I don't have environment. I did not try.). Let me know if this is not working. I will remove this post.

    #MAINWINDOW OBJECT
    window = MainWindow()
    
    #GET QWINDOW OBJECT
    win = window.windowHandle()
    
    #SET PRIMARY SCREEN
    win.setScreen(app.primaryScreen()) #app is your application object.
    

    Also there is a note in the documentation

    https://doc.qt.io/qtforpython-5/PySide2/QtGui/QWindow.html#PySide2.QtGui.PySide2.QtGui.QWindow.setScreen

    Note: If the screen is part of a virtual desktop of multiple screens, the window will not move automatically to newScreen. To place the window relative to the screen, use the screen's topLeft() position.

    You can also try by getting all the available screens

    screens = app.screens()
    

    May be you can iterate them and set the screen you want to.

    win.setScreen(screens[0]) #example