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()之后可以获取到窗口所在的屏幕
相关推荐
沫璃染墨11 小时前
《Qt从零入门系列(二):Qt开发环境搭建——从Qt Creator到SDK配置》
c++·ide·qt
xieliyu.15 小时前
Java 文件IO :File 文件类、字节流、字符流讲解
java·ide·笔记·javaee
W_chuanqi15 小时前
VSCode + Claude Code + DeepSeek:打造 AI 编程神器
ide·vscode·编辑器·ai编程
csdn_aspnet15 小时前
在 Visual Studio Code 中安装使用 Github Copilot
ide·vscode·github·copilot
sunburn-1 天前
Java 队列全面详解:从入门到面试实战
java·开发语言·汇编·ide·idea
Slow菜鸟1 天前
第3篇:实操落地篇 · 3套企业标准工作流(IDEA可视化版)
java·ide·intellij-idea
New_Horizons6661 天前
远程linux终端中支持vscode的code命令
ide·vscode·编辑器
2501_915918411 天前
免 Xcode 开发 iOS,工具链替代方案与编译、签名、安装
ide·vscode·macos·ios·个人开发·xcode·敏捷流程
赵广陆1 天前
Jupyter和PyCharm完整集成
ide·jupyter·pycharm
AttackingLin3 天前
VScode Claude Code 插件配置第三方api
ide·vscode·编辑器