pos()解析及其应用---by jzj139 整理
在QWidget class中有这样的一个函数:
QPoint QWidget::pos () const
Returns the position of the widget within its parent widget.
中文:返回一个窗口在它的父窗口中的位置。
下面我们来看看pos的属性:
QPoint pos
This property holds the position of the widget within its parent widget.
If the widget is a top-level widget, 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.
move() is virtual, and all other overloaded move() implementations in Qt call it.
Warning: Calling move() or setGeometry() inside moveEvent() can lead to infinite recursion.
中文:这个属性把握着一个窗口在它父窗口中的位置。
如果这个窗口是一个顶层的窗口,这个位置就是这个窗口在桌面是的位置(包含它的修饰框架)。
当这个位置改变的时候,如果这个窗口是可见的话,它会立即接受一个MOVE事件。如果这个窗口当前是不可见的,它会被确保在它被显示之前接受这样一个事件。
MOVE是一个虚函数,其他所有在QT中重载MOVE函数的实现都要调用它。
警告:在moveEvent()里面调用move()或setGeometry()函数会导致无穷的递归调用。
为了很好的理解pos()函数,建议参考QT参考文档中关于窗口几何结构这一节,其中介绍了两种position和窗口的区别,并附有详细的解释图。(还介绍了如何恢复窗口几何结构)
例一:(EXAMPLE中的TUX例子)如何移动一个顶级窗口部件
void MoveMe::mousePressEvent( QMouseEvent *e )
{
clickPos = e->pos();//这里只有一个顶级窗口,所以不需要使用globalPos()来指定它的绝对位置
}
void MoveMe::mouseMoveEvent( QMouseEvent *e )
{
move( e->globalPos() - clickPos );
例二:
在Qt程序窗口上点击任意区域移动窗体
方法是截取组件Widget的鼠标事件函数,自己处理鼠标点击和移动的事件.
Void MyWidget::mouseMoveEvent(QmouseEvent *e)
{
Qpoint newpos=e->globalPos();//获得鼠标相对于屏幕坐标系的位置
Qpoint upLeft=pos0+newpos-last;//获得新的窗口左上角的位置(pos0+(newpos-last))
Move(upLeft);
}
Void MyWidget::mousePressEvent(QmouseEvent *e)
{
last=e->globalPos();//获得鼠标相对于屏幕坐标系的位置
pos0= e->globalPos()-e->pos();
}
解释:
e->globalPos();//获得鼠标相对于屏幕坐标系的位置
e->pos(); //鼠标相对于窗体左上角的位置
pos0; //窗体左上角的位置
upLeft; //新的窗体左上角的位置
这里,我们取得的鼠标位置是绝对位置,即相当于桌面或者是屏幕的位置,同时也记录下窗口左上角的位置,当鼠标移动时,取得新的绝对位置,则窗口左上角的新位置应该是原来位置与鼠标移动的向量之和。