简体   繁体   中英

Qt - Implementing QKeyEvent

How do I implement keyboard listening in Qt? I have the following setup that's not working. I have two classes, gameLogic and gameView. gameView has an instance of gameLogic:

gameView::gameView(QWidget *parent)
    : QWidget(parent)
{
    logic = new gameLogic(6);
    logic->setFocusPolicy(Qt::TabFocus); //in one of the articles I read, this was supposed to fix the issue. It doesn't for me.
    this->resize(1200, 700);
    this->setStyleSheet("background-color: white");
    QString str;
    str.setNum(logic->n);
    connect(logic, SIGNAL(playerStepped(int, int)), this, SLOT(movePlayer(int, int)));    
}

And in gameLogic I am handling the keystrokes as follows:

void gameLogic::keybrdStep( QKeyEvent * keypressed )
{
    if (keypressed->key() == Qt::Key_Q) {
        _message = new QMessageBox;
        _message->setText("Q");
        _message->exec();
    }
}

No matter how many times I push the button Q, nothing happens. What am I doing wrong? Which part am I missing? I'm on Linux Mint with the latest version of Qt.

 void gameLogic::keybrdStep( QKeyEvent * keypressed ) 

Where did you get the method name "keybrdStep" from? Who do you think should call it?

The name of the method you need to override to get key presses is QWidget::keyPressEvent()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM