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()之后可以获取到窗口所在的屏幕
相关推荐
Java面试题总结4 小时前
IntelliJ IDEA 从卡顿到起飞,只用改这些。。。
java·ide·intellij-idea
Jay_Franklin8 小时前
Python 数据处理工作流:marimo、PyCharm 与数据存储
开发语言·数据仓库·ide·python·pycharm·数据分析·开源
渡我白衣9 小时前
打印宏与socket模块设计
java·linux·开发语言·c++·ide·人工智能·eclipse
酷虎软件18 小时前
分享链接+视频音频文案提取 API 接口文档
ide·macos·xcode
我命由我123452 天前
Android Studio - Android Studio 自定义预览尺寸
android·java·ide·java-ee·android studio·android-studio·android runtime
Luoxi_82 天前
Anaconda超详细的安装教程+VScode的使用
ide·vscode·编辑器
球king2 天前
CC GUI 插件:在 IDEA 中使用 CodeX
java·ide·intellij-idea
大龄牛码2 天前
从模型基座到工程范式:GPT-5.6与Grok 4.5在主流AI IDE中的架构适配与选型分析
ide·人工智能·gpt
不负信仰2 天前
Visual Studio 三月更新 —— 打造专属自定义 Agent
ide·visual studio
流量猎手2 天前
Vscode登陆服务器
服务器·ide·vscode