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()之后可以获取到窗口所在的屏幕
相关推荐
树码小子14 小时前
Pycharm解释器配置问题解决
ide·python·pycharm
FlyWIHTSKY17 小时前
idea中集成claude功能
java·ide·人工智能·intellij-idea·cloudera
weixin_4046793117 小时前
godot + vscode ai开发
ide·vscode·编辑器·游戏引擎·godot
我一定会有钱17 小时前
vscode system下载安装
ide·vscode·编辑器
2401_858286111 天前
VSCODE远程链接错误: 无法建立链接,过程试图写入的管道不存在的解决方法
ide·vscode·编辑器
一朵好运莲1 天前
Turbo Console Log插件VSCode更改log快捷键教程
ide·vscode·编辑器
IS6832 天前
视频文案提取技术全景:ASR vs OCR,哪种方案更适合你?
ide·macos·xcode
风筱2 天前
Idea的CC GUI插件安装Claude Code SDK失败
java·ide·ai编程
csdn_aspnet3 天前
Copilot能换成本地吗?VSCode接本地大模型本地化接入方案
ide·vscode·ai·ollama
大数据专业的小沉4 天前
解决PyCharm 2024.1 打开项目后持续卡顿,UI 无响应,编辑延迟明显
ide·python·pycharm