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()之后可以获取到窗口所在的屏幕
相关推荐
霸道流氓气质6 小时前
通义灵码 IDEA 插件完全使用指南
java·ide·intellij-idea
执明wa6 小时前
Android Studio 项目目录结构全方位详解
android·ide·android studio
C+-C资深大佬8 小时前
在PyCharm中创建虚拟环境的具体步骤是什么?
ide·python·pycharm
Sss_Ass13 小时前
CodeBuddy IDE(腾讯云代码助手)介绍及下载安装
ide·云计算·腾讯云
花伤情犹在14 小时前
2026 AI Agent 工具全景:执行层、编排层与 IDE 层的分工与选型
ide·人工智能
小宋102115 小时前
Mina Meeting Assistant 新手极速上手指南
ide·macos·ai·xcode·mina
jack@london15 小时前
eclipse启动tomcat6时报错OutOfMemoryError: PermGen space
java·ide·eclipse
超梦dasgg16 小时前
IDEA(IntelliJ IDEA)超详细基础使用教程
java·ide·intellij-idea
2501_9151063216 小时前
iOS开发工具有哪些?iOS 开发每个阶段的实用工具
ide·vscode·ios·objective-c·个人开发·swift·敏捷流程
OliverH-yishuihan16 小时前
【保姆级教程】Win11 下从零部署 Claude Code:本地环境配置 + VSCode 可视化界面全流程指南
ide·vscode·编辑器