【问题标题】:Qt keeping mouse centeredQt保持鼠标居中
【发布时间】:2012-03-19 17:29:25
【问题描述】:

我想知道是否有人有技巧将鼠标位置保持在 Qt 的 (QGL) 小部件的中心。我读到可以在找到增量后设置鼠标位置,但这种方式对我来说非常有问题。鼠标事件没有正确注册,即使注册了,也很烦人。

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);
}

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

【问题讨论】:

  • 人们倾向于对“窃取”光标的应用程序皱眉,你能详细说明你为什么要这样做吗?可能有更好的解决方案。
  • 这是一个带有 GUI 的应用程序,但是其中一个小部件需要鼠标不要触摸屏幕边缘,就像第一人称射击游戏一样,即始终保持居中。
  • 但是一旦进入小部件,用户是如何离开的呢?第一人称射击游戏也隐藏光标,并使用鼠标移动增量。我使用 QGLWidget 来显示 CAD 数据,用户使用鼠标在场景中导航,并且每次像素变化(刷新率)都会给我鼠标事件。所以一个更好的问题是为什么你的鼠标事件不密集?您是否覆盖了QWidget::mouseMoveEvent(QMouseEvent* event)
  • 我上传了我的鼠标代码,如您所见,我在每个 mousemoveevent 更新“播放器”位置。

标签: qt fixed mouse-cursor


【解决方案1】:

固定:

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);
}

【讨论】:

  • 但是当您调用QCursor::setPos 时,如何防止再次调用mouseMoveEvent?我尝试了类似的方法,但问题是它只会导致控件“摆动”,因为每个动作都会立即反转。
  • 抱歉,我在这方面工作了很长时间,我根本不记得有任何问题。可能是 Qt 框架发生了变化并引入了这个问题。
猜你喜欢
  • 2013-04-15
  • 2013-04-24
  • 2011-11-26
  • 1970-01-01
  • 1970-01-01
  • 2011-05-19
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多