我想知道是否有人有诀窍将鼠标位置保持在Qt的(QGL)小部件中心。我读到可以在找到delta之后设置mouseposition,但这种方式对我来说非常麻烦。鼠标事件没有正确注册,如果它们发生了任何事情,那么它们会非常跳跃。
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 :(得分: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);
}