QT|windwos桌面端应用程序开发,当连接多个显示器的时候,如何获取屏幕编号?

在 Qt 中(包括 Qt 5/6),获取屏幕编号 可以通过以下方式实现:

✅ 推荐方式(Qt 5.6+ 及 Qt 6)

使用 QScreenQGuiApplication 的 API,这是现代 Qt 推荐的方式,兼容性好,支持高 DPI:

cpp 复制代码
#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 指针),可以用:

cpp 复制代码
int screenIndex = QApplication::desktop()->screenNumber(this);

⚠️ 注意:QDesktopWidget 在 Qt 6 中已废弃,建议用以下方式替代:

cpp 复制代码
QScreen *screen = this->window()->windowHandle()->screen();
int screenIndex = QGuiApplication::screens().indexOf(screen);

✅ 获取鼠标所在屏幕编号(可用于初始化)

cpp 复制代码
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,建议完全使用 QScreenQWindow,避免使用 QDesktopWidget

如需将窗口移动到指定屏幕,可使用:

cpp 复制代码
QScreen *targetScreen = QGuiApplication::screens()[screenIndex];
window->setScreen(targetScreen);
window->show();

如你仍在使用 Qt 5 并兼容旧代码,也可使用 QDesktopWidget,但建议逐步迁移至 QScreen

相关推荐
我是菜鸟0713号1 天前
Qt 中 OPC UA 通讯实战
开发语言·qt
JCBP_1 天前
QT(4)
开发语言·汇编·c++·qt·算法
Brookty1 天前
【JavaEE】线程安全-内存可见性、指令全排序
java·开发语言·后端·java-ee·线程安全·内存可见性·指令重排序
百锦再1 天前
[特殊字符] Python在CentOS系统执行深度指南
开发语言·python·plotly·django·centos·virtualenv·pygame
Anson Jiang1 天前
浏览器标签页管理:使用chrome.tabs API实现新建、切换、抓取内容——Chrome插件开发从入门到精通系列教程06
开发语言·前端·javascript·chrome·ecmascript·chrome devtools·chrome插件
会开花的二叉树1 天前
继承与组合:C++面向对象的核心
java·开发语言·c++
长河1 天前
Java开发者LLM实战——LangChain4j最新版教学知识库实战
java·开发语言
Cyan_RA91 天前
SpringMVC @RequestMapping的使用演示和细节 详解
java·开发语言·后端·spring·mvc·ssm·springmvc
再见晴天*_*1 天前
SpringBoot 中单独一个类中运行main方法报错:找不到或无法加载主类
java·开发语言·intellij idea
lqjun08271 天前
Qt程序单独运行报错问题
开发语言·qt