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

27 篇文章 0 订阅

一、功能要求:

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

    避免出现下面的问题:

    

二、功能分析:

      想法: 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()就变成相对父对象的相对位置了。

 

 

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值