• Qt 实现点击主窗口内任意位置,在其位置弹窗弹窗,且弹窗必须在主窗口的换位内


    一、功能要求:

         实现点击主窗口内任意位置,在其位置弹窗弹窗,且弹窗必须在主窗口的换位内。

        避免出现下面的问题:

        

    二、功能分析:

          想法:

    1、只要确定弹窗左上角的合理位置就可以了。

    2、合理位置: 简单的一种就是保证其必在主窗口内。思路就是,判断弹窗左上角和右下角的坐标值是否超过主窗口的边界值来重新设置弹窗的左上角的坐标值。

    三、代码实现:

     1 // mouseGPos : 当前鼠标的绝对坐标
     2 // pMainWgt : 主窗口
     3 // pPopWgt : 弹窗
     4 QPoint CToolBarWgt::getFixGlobalPos(QPoint mouseGPos, QWidget* pMainWgt, QWidget* pPopWgt)
     5 {
     6     QPoint mianGPoint = pMainWgt->mapToGlobal(pMainWgt->pos());
     7     int nMainLeft = mianGPoint.x();
     8     int nMainTop = mianGPoint.y();
     9     int nMainRight = mianGPoint.x()+ pMainWgt->width();
    10     int nMainBottom = mianGPoint.y() + pMainWgt->height(); 
    11  
    12     int nPopLeft = mouseGPos.x() - pPopWgt->width()/2 ;
    13     int nPopTop = mouseGPos.y() - pPopWgt->height();
    14     int nPopRight = mouseGPos.x() + pPopWgt->width()/2;
    15     int nPopBottom = mouseGPos.y();
    16  
    17     // 最终要确定的只有左上角的坐标位置: 
    18     nPopLeft = nPopLeft < nMainLeft ? nMainLeft: nPopLeft;  // 弹窗左边超出主窗口,赋值为主窗口边界值。
    19     nPopTop = nPopTop < nMainTop ? nMainTop : nPopTop; //弹窗上部分超出主窗口上部值,赋值为主窗口上半边界值。
    20     nPopLeft = nPopRight > nMainRight ? nPopLeft - (nPopRight - nMainRight) : nPopLeft; //弹窗右侧超出主窗口右侧边界值,则弹窗左侧值向左移动超出的部分
    21     nPopTop = nPopBottom > nMainBottom ? nPopTop - (nPopBottom - nMainBottom): nPopTop; //弹窗下侧超出主窗口下侧边界值,则弹窗上侧值向上移动超出的部分
    22     // 返回的QPoint是绝对坐标。
    23     return QPoint(nPopLeft, nPopTop);
    24 }

    四、疑问

       为什么弹窗明明有设置父类,并且其父类也有设置主窗口为父类。当时该弹窗在this->move(x,y)的时候,x,y却是绝对坐标下的值。【ps:上面内容绝对可靠没错】

       突然想到是否为下面内容中某个设置后导致的

    1     setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
    2     setAttribute(Qt::WA_TranslucentBackground, true);

    其中弹窗是继承于QWidget的窗口。

    因为Qt4 文档中说:

    pos : QPoint
    This property holds the position of the widget within its parent widget.
    
    If the widget is a window, the position is that of the widget on the desktop, including its frame.
    
    When changing the position, the widget, if visible, receives a move event (moveEvent()) immediately. If the widget is not currently visible, it is guaranteed to receive an event before it is shown.
    
    By default, this property contains a position that refers to the origin.

    结果:证实确实是 setWindowFlags(Qt::Tool)导致的move的时候是按照绝对坐标(显示器)来移动的。

     因为把这个移除后,其move()就变成相对父对象的相对位置了。

  • 相关阅读:
    编译原理笔记 2
    编译原理笔记 1
    初步学习计算机图形学 [闫令琪]
    复杂 Web 前端的设计
    使用 GitHub Actions 部署 .Net 5 程序
    ES 2020 Optional Chain (可选链)
    2020 Web 前端学习记录
    WPF TreeView 支持多选
    linux (CentOS 7)报错:yum 命令报错 “ Cannot find a valid baseurl for repo: base/7/x86_6 ”
    node.js 报错
  • 原文地址:https://www.cnblogs.com/ybqjymy/p/13565679.html
Copyright © 2020-2023  润新知