2012-03-19 38 views
1

我想知道是否有人有一个技巧来保持鼠标位置在Qt(QGL)小部件中居中。我读到可以在找到三角洲后设置鼠标位置,但这种方式对我来说很有用。鼠标事件没有正确注册,如果他们这样做,非常跳动。Qt保持鼠标居中

void World::mouseMoveEvent(QMouseEvent *event) 
{ 
    if (event->buttons() & Qt::LeftButton) { 

     GLfloat dx = GLfloat(event->x() - lastPos.x())/width(); 
     GLfloat dy = GLfloat(event->y() - lastPos.y())/height(); 

     player->rotHorizontal += 360.0 * dx; 
     if(player->rotHorizontal < 0.0) 
      player->rotHorizontal += 360.0; 
     else if(player->rotHorizontal > +360.0) 
      player->rotHorizontal -= 360.0; 

     player->rotVertical += 360.0 * dy; 

     if (player->rotVertical > MAX_ROTATION_UP) { 
      player->rotVertical = MAX_ROTATION_UP; 
     } else if (player->rotVertical < -MAX_ROTATION_UP) { 
      player->rotVertical = -MAX_ROTATION_UP; 
     } 

    } 
// int diffX = event->pos().x() - lastPos.x() % 20; 
// int diffY = event->pos().y() - lastPos.y() % 20; 
// if (diffY > 10 || diffX > 10 || diffY < -10 || diffX < -10) { 
//  QPoint glob = mapToGlobal(QPoint(this->pos().x() + width()/2, this->pos().y() + height()/2)); 
//  QCursor::setPos(glob); 
// } 
    lastPos = event->pos(); 
    QGLWidget::mouseMoveEvent(event); 
} 

我注释掉了会保持鼠标居中的代码。如果这可行,我会把它放在左键区域。

+0

人们往往皱眉说“窃取”应用中的光标,你可以在你为什么要这么做详细点吗?可能有更好的解决方案。 – cmannett85 2012-03-20 07:54:39

+0

它是一个带有GUI的应用程序,但其中一个小部件需要鼠标不要触摸屏幕的边缘,就像第一人称射击游戏一样,即始终保持居中。 – RobotRock 2012-03-20 12:58:29

+1

但是用户一旦进入就如何离开小部件?也是第一人称射击者隐藏光标,并使用鼠标移动增量。我使用QGLWidget显示CAD数据,用户使用鼠标在场景中导航,鼠标事件给我每一个像素的改变(刷新率)。所以更好的问题是为什么你的鼠标事件不密集?你是否重写'QWidget :: mouseMoveEvent(QMouseEvent * event)'? – cmannett85 2012-03-20 13:18:00

回答

2

修正:

void World::mouseMoveEvent(QMouseEvent *event) 
{ 
    if (event->buttons() & Qt::LeftButton) { 

     GLfloat dx = GLfloat(event->x() - lastPos.x())/width(); 
     GLfloat dy = GLfloat(event->y() - lastPos.y())/height(); 

     player->rotHorizontal += 360.0 * dx; 
     if(player->rotHorizontal < 0.0) 
      player->rotHorizontal += 360.0; 
     else if(player->rotHorizontal > +360.0) 
      player->rotHorizontal -= 360.0; 

     player->rotVertical += 360.0 * dy; 

     if (player->rotVertical > MAX_ROTATION_UP) { 
      player->rotVertical = MAX_ROTATION_UP; 
     } else if (player->rotVertical < -MAX_ROTATION_UP) { 
      player->rotVertical = -MAX_ROTATION_UP; 
     } 

    } 
    QPoint glob = mapToGlobal(QPoint(width()/2,height()/2)); 
    QCursor::setPos(glob); 
    lastPos = QPoint(width()/2,height()/2); 
    QGLWidget::mouseMoveEvent(event); 
} 
+0

但是,当你调用'QCursor :: setPos'时,如何避免再次调用'mouseMoveEvent'?我尝试了类似的东西,并且遇到问题,它会导致控件“摆动”,因为每个动作都会立即反转。 – user1488118 2015-11-11 12:43:18

+0

对不起,我工作了这么久,我不记得有这个问题。这可能是Qt框架改变并引入了这个问题。 – RobotRock 2015-11-11 12:47:15