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()之后可以获取到窗口所在的屏幕
相关推荐
这是个栗子6 小时前
【问题解决】VSCode终端中看不到Git-Bash
ide·git·vscode
岁月玲珑9 小时前
【使用Android Studio调试手机app时候手机老掉线问题】
android·ide·android studio
木头没有瓜14 小时前
vscode离线安装插件
ide·vue.js·vscode
lls23316 小时前
恢复idea文件目录
ide
NeRF_er17 小时前
使用 VScode Debug加不上断点的原因
ide·vscode·编辑器
GHL28427109017 小时前
error MSB8041: 此项目需要 MFC 库。从 Visual Studio 安装程序(单个组件选项卡)为正在使用的任何工具集和体系结构安装它们。
ide·visual studio
笑醉踏歌行1 天前
idea应用代码配色网站
java·ide·intellij-idea
韩初心2 天前
使用 visual studio 2022 编译 Lua5.4.8
ide·visual studio·lua5.4
comeilmforever2 天前
IDEA2025 Version Control 窗口 local changes显示
java·ide·intellij-idea
kiss strong2 天前
好用的自带AI功能的国产IDE
ide