QML中Qt.application.screens[0]行为疑问及获取首个屏幕方法咨询
1. Is the screen: Qt.application.screens[0] behavior expected?
Short answer: This behavior doesn’t match the assumption that screens[0] is a fixed "first physical screen", but it’s a documented platform-specific quirk in Qt 5.x.
From your testing, you saw that setting screen to Qt.application.screens[0] makes the window pop up on the screen where your mouse was when the app launched, while screens[1] consistently targets your second monitor. This happens because the order of screens in Qt.application.screens isn’t guaranteed to be tied to physical screen positions. On some window systems (like X11 or certain Windows configurations), Qt may prioritize the screen holding the mouse cursor or active focus as the first element in the list when the app starts up.
This isn’t a bug—it’s just behavior driven by how the underlying OS reports screen information to Qt. The screens list order is determined by the operating system, not a fixed physical layout.
2. How to get the "true first screen"?
The definition of "true first screen" depends on your needs: it could be the system’s designated primary screen, or the screen positioned at the leftmost/topmost physical coordinate. Here are two reliable solutions:
Option 1: Use the system's primary screen
Qt provides a dedicated property for the system’s primary screen (the one set as main in your OS display settings), which stays consistent no matter where your mouse is:
Window { id: main visible: true width: 500 height: 500 screen: Qt.application.primaryScreen // Fixed to system primary screen Text { text: "Hello World!" } }
Option 2: Get the screen with the leftmost (or topmost) physical position
If you need the screen that’s physically first (e.g., leftmost in a horizontal multi-monitor setup), you can sort screens by their global coordinates with a small QML function:
Window { id: main visible: true width: 500 height: 500 function getLeftmostScreen() { let targetScreen = Qt.application.screens[0]; Qt.application.screens.forEach(screen => { // Compare X coordinates for horizontal layout; use Y for vertical stacks if (screen.x < targetScreen.x) { targetScreen = screen; } }); return targetScreen; } screen: getLeftmostScreen() Text { text: "Hello World!" } }
This function loops through all available screens and picks the one with the smallest x coordinate (swap to y if your monitors are stacked vertically). This gives you a consistent "physical first screen" regardless of mouse position or the OS-reported list order.
内容的提问来源于stack exchange,提问作者TFM

