Qt自定义标题栏的多屏适配

标题栏自定义

参考博客 : https://blog.csdn.net/goforwardtostep/article/details/53494800

多屏适配

MyTitleBar类抽象定义了自定义标题栏,使用起来相对方便。但是在多屏情况下,窗口初次显示只能在主屏幕上,如果拖到其他屏幕上最大化,还会回到主屏。

处理方式如下:

  • 获取当前屏幕的索引

    c++ 复制代码
    /* MyTitleBar 的 mouseMoveEvent 函数*/
    void MyTitleBar::mouseMoveEvent(QMouseEvent *event) {
        if (_isPressed) {
            QPoint movePoint = event->globalPos() - _startMovePos;
            QPoint widgetPos = this->parentWidget()->pos();
            _startMovePos = event->globalPos();
            this->parentWidget()->move(widgetPos.x() + movePoint.x(), widgetPos.y() + movePoint.y());
            // 每次移动后 获取当前屏幕的索引
            currentScreenIndex = QApplication::desktop()->screenNumber(this->parentWidget);
        }
        return QWidget::mouseMoveEvent(event);
    }
  • 根据索引获取屏幕大小信息(QRect)

    c++ 复制代码
    /*使用MyTitleBar的窗口*/
    void MainPage::onButtonMaxClicked() {
        _titleBar->saveRestoreInfo(this->pos(),QSize(this->width(),this->height()));
        QRect desktopRect = QApplication::desktop()->availableGeometry(_titleBar->getCurrentScreenIndex()); // availableGeometry(int) 传入索引值,获取目标屏幕的QRect
        QRect factRect = QRect(desktopRect.x()-3,desktopRect.y()-3, desktopRect.width()+6,desktopRect.height()+6);
        setGeometry(factRect);
    }

注意事项:

  • QApplication::desktop()->screenNumber() 函数默认获取的是主屏幕的索引,通过传入QWidget*参数获取当前窗口所在屏幕
  • 获取屏幕大小有两个函数: QApplication::desktop()->availableGeometry(no), QApplication::desktop()->screenGeometry(no);尽量使用 QApplication::desktop()->availableGeometry(no),availableGeometry函数获取的是可用屏幕大小(除去任务栏)
  • availableGeometry 与 screenGeometry不传参数时获取的是主屏幕的大小
  • 不要在QWidget的showEvent中获取屏幕的索引,此时获取的都是主屏幕,在QWidget.show()之后可以获取到窗口所在的屏幕
相关推荐
wenzhangli77 小时前
AI-IDE 关键技术解析:从自然语言到企业级智能开发平台的架构演进
ide·人工智能·架构
${王小剑}8 小时前
在pycharm中配置pyside6
ide·python·pycharm
youcans_12 小时前
【跟我学 AI 编程】(6) Claude Code 与 IDE 的集成
ide·人工智能·ai编程·claude code
闪电悠米13 小时前
黑马点评-秒杀优化-01_async_seckill_idea
java·数据库·ide·redis·分布式·缓存·intellij-idea
摇滚侠13 小时前
IDEA 创建 Java 项目 lib 和 resources
java·ide·intellij-idea
仰望星空的凡人14 小时前
VSCODE接入Claude Code使用第三方模型教程
ide·vscode·ai智能体·claude code
棒棒的唐1 天前
Vscode Continue插件 集成 本地llama.cpp大模型实现代码补全
ide·vscode·编辑器
bush41 天前
vscode编辑设备树插件 devicetree LSP
ide·vscode·里氏替换原则
摇滚侠2 天前
IDEA 新建 JavaWeb 项目 Tomcat 和 Servlet
java·ide·intellij-idea
万粉变现经纪人2 天前
2026最新Windows11系统CMD安装Claude Code 快速接入DeepSeek V4 Pro在VSCode编程工具中使用保姆级入门教程指南
linux·运维·ide·windows·vscode·macos·编辑器