qt keypressevent()中的多个键

时间:2014-05-03 22:37:47

标签: c++ qt qwidget qtgui qevent

我试图在Qt上创建一个游戏,玩家可以对角线。因此,当我按下W和D时,玩家可以转到右上角。但是,当我先按W,然后按D,然后按D,玩家不会按W方向。事实上,即使被发信号通知调用keypressevent()函数,也不会持有W键。 但是,当我按W,然后按D,然后释放W时,角色沿D方向移动。

以下是我的代码:

void my_qscroll::keyPressEvent(QKeyEvent *event)
{
    switch ( event->key() )
    {
    case Qt::Key_W:
        key[0] = 1;
        break;
    case Qt::Key_A:
        key[1] = 1;
        break;
    case Qt::Key_S:
        key[2] = 1;
        break;
    case Qt::Key_D:
        key[3] = 1;
        break;
    }

    for(int i = 0; i != 4 ; i++)
    {
        if(key[i] == 1)
        {
            this->B = i;
            emit Move();
        }
    }
}

void my_qscroll::keyReleaseEvent(QKeyEvent *event)
{
    switch ( event->key() )
    {
    case Qt::Key_W:
        key[0] = 0;
        qDebug() << "released W";
        break;
    case Qt::Key_A:
        key[1] = 0;
        qDebug() << "released A";
        break;
    case Qt::Key_S:
        key[2] = 0;
        qDebug() << "released S";
        break;
    case Qt::Key_D:
        key[3] = 0;
        qDebug() << "released D";
        break;
    }
}

我不确定如何解决这个问题。任何帮助我的想法或链接都会很棒。先感谢您。

1 个答案:

答案 0 :(得分:1)

你需要这样的东西:

void my_qscroll::keyPressEvent(QKeyEvent *event)
{
    switch ( event->key() )
    {
    case Qt::Key_W:
        key[0] = 1;
        break;
    case Qt::Key_A:
        key[1] = 1;
        break;
    case Qt::Key_S:
        key[2] = 1;
        break;
    case Qt::Key_D:
        key[3] = 1;
        break;
    }

    for(int i = 0; i != 4 ; i++)
    {
        if(key[i] == 1)
        {
            this->B = i;
            emit Move();
        }
    }
}

void my_qscroll::keyReleaseEvent(QKeyEvent *event)
{
    switch ( event->isAutoRepeat() )
    {
    case Qt::Key_W:
        key[0] = 0;
        qDebug() << "released W";
        break;
    case Qt::Key_A:
        key[1] = 0;
        qDebug() << "released A";
        break;
    case Qt::Key_S:
        key[2] = 0;
        qDebug() << "released S";
        break;
    case Qt::Key_D:
        key[3] = 0;
        qDebug() << "released D";
        break;
    }
}

void my_qscroll::movePlayer() {
  if (key[1] && key[0]) {
      left -= 2;
      top -= 2;
  } else if (key[3] && key[0]) {
      left += 2;
      top -= 2;
  } else if (key[2] && key[1]) {
      left -= 2;
      top += 2;
  } else if (key[2] && key[3]) {
      left += 2;
      top += 2;
  } else if (key[3]) {
      left += 2;
  } else if (key[1]) {
      left -= 2;
  } else if (key[2]) {
      top += 2;
  } else if (key[0]) {
      top -= 2;
  }
}

void myCanvas::updateEnv() {
    emit Move();
    repaint();
}