QT|windwos桌面端应用程序开发,当连接多个显示器的时候,如何获取屏幕编号?
在 Qt 中(包括 Qt 5/6),获取屏幕编号 可以通过以下方式实现:
✅ 推荐方式(Qt 5.6+ 及 Qt 6)
使用 QScreen
和 QGuiApplication
的 API,这是现代 Qt 推荐的方式,兼容性好,支持高 DPI:
#include <QGuiApplication>
#include <QScreen>
#include <QDebug>int main(int argc, char *argv[])
{QGuiApplication app(argc, argv);QList<QScreen*> screens = QGuiApplication::screens();qDebug() << "屏幕数量:" << screens.size();for (int i = 0; i < screens.size(); ++i) {qDebug() << "屏幕编号:" << i<< "分辨率:" << screens[i]->size()<< "位置:" << screens[i]->geometry().topLeft();}return 0;
}
screens()
返回一个QScreen*
列表,索引即为屏幕编号。- 主屏幕通常为
screens[0]
,但不绝对,需用QGuiApplication::primaryScreen()
确认。
✅ 获取窗口所在屏幕编号(Qt Widgets 程序)
如果你有一个 QWidget
窗口(如 this
指针),可以用:
int screenIndex = QApplication::desktop()->screenNumber(this);
⚠️ 注意:
QDesktopWidget
在 Qt 6 中已废弃,建议用以下方式替代:
QScreen *screen = this->window()->windowHandle()->screen();
int screenIndex = QGuiApplication::screens().indexOf(screen);
✅ 获取鼠标所在屏幕编号(可用于初始化)
QPoint cursorPos = QCursor::pos();
int screenIndex = -1;
for (int i = 0; i < QGuiApplication::screens().size(); ++i) {if (QGuiApplication::screens().at(i)->geometry().contains(cursorPos)) {screenIndex = i;break;}
}
⚠️ 注意事项
- Windows 设置中的编号(如 1、2)与 Qt 的编号无关,Qt 的编号是从 0 开始的逻辑索引。
- 如果你使用的是 Qt 6,建议完全使用
QScreen
和QWindow
,避免使用QDesktopWidget
。
如需将窗口移动到指定屏幕,可使用:
QScreen *targetScreen = QGuiApplication::screens()[screenIndex];
window->setScreen(targetScreen);
window->show();
如你仍在使用 Qt 5 并兼容旧代码,也可使用 QDesktopWidget
,但建议逐步迁移至 QScreen
。