一、功能要求:
实现点击主窗口内任意位置,在其位置弹窗弹窗,且弹窗必须在主窗口的换位内。
避免出现下面的问题:
二、功能分析:
想法: 1、只要确定弹窗左上角的合理位置就可以了。
2、合理位置: 简单的一种就是保证其必在主窗口内。思路就是,判断弹窗左上角和右下角的坐标值是否超过主窗口的边界值来重新设置弹窗的左上角的坐标值。
三、代码实现:
// mouseGPos : 当前鼠标的绝对坐标
// pMainWgt : 主窗口
// pPopWgt : 弹窗
QPoint CToolBarWgt::getFixGlobalPos(QPoint mouseGPos, QWidget* pMainWgt, QWidget* pPopWgt)
{
QPoint mianGPoint = pMainWgt->mapToGlobal(pMainWgt->pos());
int nMainLeft = mianGPoint.x();
int nMainTop = mianGPoint.y();
int nMainRight = mianGPoint.x()+ pMainWgt->width();
int nMainBottom = mianGPoint.y() + pMainWgt->height();
int nPopLeft = mouseGPos.x() - pPopWgt->width()/2 ;
int nPopTop = mouseGPos.y() - pPopWgt->height();
int nPopRight = mouseGPos.x() + pPopWgt->width()/2;
int nPopBottom = mouseGPos.y();
// 最终要确定的只有左上角的坐标位置:
nPopLeft = nPopLeft < nMainLeft ? nMainLeft: nPopLeft; // 弹窗左边超出主窗口,赋值为主窗口边界值。
nPopTop = nPopTop < nMainTop ? nMainTop : nPopTop; //弹窗上部分超出主窗口上部值,赋值为主窗口上半边界值。
nPopLeft = nPopRight > nMainRight ? nPopLeft - (nPopRight - nMainRight) : nPopLeft; //弹窗右侧超出主窗口右侧边界值,则弹窗左侧值向左移动超出的部分
nPopTop = nPopBottom > nMainBottom ? nPopTop - (nPopBottom - nMainBottom): nPopTop; //弹窗下侧超出主窗口下侧边界值,则弹窗上侧值向上移动超出的部分
// 返回的QPoint是绝对坐标。
return QPoint(nPopLeft, nPopTop);
}
四、疑问
为什么弹窗明明有设置父类,并且其父类也有设置主窗口为父类。当时该弹窗在this->move(x,y)的时候,x,y却是绝对坐标下的值。【ps:上面内容绝对可靠没错】
突然想到是否为下面内容中某个设置后导致的
setWindowFlags(Qt::FramelessWindowHint | Qt::Tool);
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()就变成相对父对象的相对位置了。