Qt即时响应来自keybaord的按键

Qt instant response to a pressed key from keybaord

本文关键字:keybaord 响应 Qt      更新时间:2023-10-16

我正在尝试用键盘上的箭头键向左或向右移动摇杆。下面的这段代码可以一步一步地完成,我的意思是,无论我握着键盘上的向左箭头还是只是点击它,摇杆只能移动 5 个单位。我想做的是只要我握着钥匙就移动它。

bool handled = false;
if ( e->type() == QEvent::KeyPress )
{
    QKeyEvent *keyEvent = (QKeyEvent *)e;
    if ( keyEvent->key() == Qt::Key_Left )
    {
        left= (= == 0 ? -5 : 0);
        handled = true;
    }
    else if ( keyEvent->key() == Qt::Key_Right )
    {
        right= (right== 0 ? 5 : 0);
        handled = true;
    }
}

我在 QKeyEvent 类中找不到适用于我想做的事情的方法。我该如何解决这个问题?

你为什么不使用 QAction?例如,捕捉左键按下:

    QAction *action = new QAction("test", this);
    action->setShortcut(QKeySequence("Left"));
    this->addAction(action);
    this->connect(action, SIGNAL(triggered()), this, SLOT(left_button_slot()));

和一个插槽

void Widget::left_button_slot()
{
    //do whatever you want
    QMessageBox::information(this, "Hey", "You pressed left key !");
}