最近看了些代码,被各种pos(), globalpos()之类的差异搞迷糊了,心想来整理一下区别,主要看help,个人理解,不一定对,若有大佬路过,不吝指点,幸甚。
用图片来说明一下可能更清楚,总得来说应该有3个坐标系:
1、全局的桌面坐标系,坐标轴原点为O1,
2、widget的父widget坐标系,主要用于定位当前widget在父widget中的位置,原点为当前widget的父widget的左上角位置,这里为O2
3、widget坐标系,用于定位widget内部位置,坐标轴原点为O3
Returns the position of the cursor (hot spot) of the primary screen in global screen coordinates. 返回鼠标在全局坐标位置,即相对于桌面坐标系统原点O1的坐标位置
This property holds the position of the widget within its parent widget
这个属性表示的是当前widget相对于其父widget的位置,(这边widget的parent为Mainwindow)即当前widget的左上角O3点,在以O2为坐标轴原点的坐标位置。widget没有移动,pos()也是不变的,跟鼠标点位置没关系。
If the widget is a window, the position is that of the widget on the desktop, including its frame.如果widget是个窗口,pos()表示widget在桌面的位置,包含边框
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.懒得翻,单纯觉着这段精辟。
注:pos().x() 有时候直接写成x(),效果是一致的
Returns the position of the mouse cursor, relative to the widget that received the event.
返回鼠标相对于接收鼠标事件的widget的位置,即坐标原点(0,0)是接收鼠标事件的widget的左上角,即O3
Returns the global position of the mouse cursor at the time of the event.
返回鼠标事件发生时,鼠标的全局位置,从示例1可以看出,跟在鼠标事件中直接使用QCursor::pos()效果是相同的
Translates the global screen coordinate pos to widget coordinates.
将相对于屏幕的全局坐标转换为相对于widget的坐标
由示例1也可以看出 mapFromGlobal(this->cursor().pos()) 的结果和event->pos()是一致的,其中this是接收鼠标事件的widget
Translates the widget coordinate pos to global screen coordinates
示例1、
在鼠标事件中: qDebug() << this->cursor().pos() << pos() << event->globalPos()
<< event->pos() << mapFromGlobal(this->cursor().pos()) << endl;
在不同位置点击几次,输出
QPoint(476,202) QPoint(459,185) QPoint(476,202) QPoint(17,17) QPoint(17,17)
QPoint(483,203) QPoint(459,185) QPoint(483,203) QPoint(24,18) QPoint(24,18)
QPoint(467,191) QPoint(459,185) QPoint(467,191) QPoint(8,6) QPoint(8,6)
示例2、在实现一个可以自由拖动位置的widget时:
void ShadowWidget::mousePressEvent(QMouseEvent *event)
{
if (event->button() == Qt::LeftButton && !mouse_press) {
mouse_press = true;
}
//窗口移动距离
orig_point = event->globalPos();
orig_pos = pos() ;
}
void ShadowWidget::mouseReleaseEvent(QMouseEvent *)
{
if (mouse_press) {
mouse_press = false;
}
}
void ShadowWidget::mouseMoveEvent(QMouseEvent *event)
{
//移动窗口
if (mouse_press) {
QPoint move_point = event->globalPos();
move(move_point - orig_point + orig_pos );
/*move是相对于桌面系统来移动widget,所以是相对于移动前
widget在桌面系统的位置上来进行的,
所以要加上orig_pos*/
}
}
在坐标位置变换时注意下不同坐标系的坐标轴原点差异,就能灵活应对了。