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

相关推荐
万粉变现经纪人14 分钟前
如何解决 pip install -r requirements.txt 无效可编辑项 ‘e .‘(-e 拼写错误)问题
开发语言·python·r语言·beautifulsoup·pandas·pip·scipy
say_fall30 分钟前
精通C语言(2.结构体)(内含彩虹)
c语言·开发语言·windows
潇凝子潇30 分钟前
在使用Nacos作为注册中心和配置中心时,如何解决服务发现延迟或配置更新不及时的问题
开发语言·python·服务发现
长源Gingko41 分钟前
Windows中在QTCreator中调试,提示缺少debug information files问题的解决
windows·qt
纵横八荒1 小时前
Java基础加强13-集合框架、Stream流
java·开发语言
欣然~2 小时前
百度地图收藏地址提取与格式转换工具 说明文档
java·开发语言·dubbo
William_cl2 小时前
C# MVC 修复DataTable时间排序以及中英文系统的时间筛选问题
开发语言·c#·mvc
running thunderbolt2 小时前
项目---网络通信组件JsonRpc
linux·服务器·c语言·开发语言·网络·c++·性能优化
小马学嵌入式~2 小时前
堆排序原理与实现详解
开发语言·数据结构·学习·算法
SundayBear2 小时前
Qt 开发修炼指南:从入门到通透的实战心法
开发语言·qt·嵌入式