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()之后可以获取到窗口所在的屏幕
相关推荐
2501_941823064 小时前
强化学习在边缘AI智能控制中的应用与多语言实现实践指南
ide
Pocker_Spades_A16 小时前
在家写的代码,办公室接着改?Jupyter通过cpolar实现远程访问这么玩
ide·python·jupyter
liwulin050616 小时前
【ESP32-S3-CAM】如何在Arduino IDE中关闭调试
ide
三更两点17 小时前
第196期 TRAE 与 Amazon Kiro 智能体驱动集成开发环境(Agentic IDE)对比
ide
ol木子李lo1 天前
Visual studio 2022高亮汇编(ASM)语法方法
汇编·ide·windows·visual studio
曹牧2 天前
Eclipse为方法添加注释
java·ide·eclipse
zandy10112 天前
2025年11月AI IDE权深度测榜:深度分析不同场景的落地选型攻略
ide·人工智能·ai编程·ai代码·腾讯云ai代码助手
youngerwang2 天前
【字节跳动 AI 原生 IDE TRAE 】
ide·人工智能·trae
youngerwang2 天前
AI 编程环境与主流 AI IDE 对比分析报告
ide·人工智能
猿小猴子2 天前
主流 AI IDE 之一的 Google Antigravity IDE 介绍
ide·人工智能·google·antigravity