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()之后可以获取到窗口所在的屏幕
相关推荐
sinat_2554878110 小时前
第七部分。介绍MVC(模型-视图-控制器)模式
java·ide·http·tomcat·intellij-idea
Algorithm_Engineer_13 小时前
如何利用Pycharm进行分布式的Debug训练
ide·分布式·pycharm
Jumbo星14 小时前
新版vscode侧边资源管理器的文件搜索
ide·vscode·编辑器
ABAP-張旺15 小时前
ABAP:Visual Studio Code開發ABAP教程
ide·vscode·编辑器
stevenzqzq18 小时前
vsCode AI插件
ide·人工智能·vscode
恣艺20 小时前
解决 PyCharm 2024.1+ matplotlib 图表显示异常:Plots 工具窗口空白 / tostring_rgb 报错
ide·pycharm·matplotlib
专注VB编程开发20年21 小时前
阿里通义灵码插件安装失败
开发语言·ide·c#·visual studio
李少兄21 小时前
IDE 提示 “GitLab versions older than 14.0 are not supported” 的深度排查与解决方案
ide·gitlab
司悠1 天前
【解决在vscode里开服务器登录codeX后发消息会一直reconnecting】
服务器·ide·vscode
Allenliu _Andy1 天前
2026 最新版|免登录适配国内网络 Claude Code 终端版安装配置教程(Windows)
ide·chatgpt·openai·ai编程·claude code