PDA

View Full Version : keyPressEvent Key_Up/Down/Right//Left



laurynas2003
29th April 2020, 18:00
Hello,

Could someone tell me why my keyPressEvent doesn't work when I use arrow keys?
When I use Qt::Key_W/S/D/A everything works fine.



void MainWindow::keyPressEvent(QKeyEvent *event)
{
switch (event->key()) {
case Qt::Key_Up:
if (current_square_y != 0 && is_legal_move(current_square_y, current_square_x, current_square_y -1, current_square_x)){

current_square_y--;

background_color_squares[current_square_y][current_square_x]->setBrush(start_and_path_background_color);
background_color_squares[previous_square_cord.first][previous_square_cord.second]->setBrush(maze_background_color);
previous_square_cord = {current_square_y, current_square_x};

square_moved++;

}break;
case Qt::Key_Down:
if (current_square_y != maze_height - 1 && is_legal_move(current_square_y, current_square_x, current_square_y + 1, current_square_x)){

current_square_y++;

background_color_squares[current_square_y][current_square_x]->setBrush(start_and_path_background_color);
background_color_squares[previous_square_cord.first][previous_square_cord.second]->setBrush(maze_background_color);
previous_square_cord = {current_square_y, current_square_x};

square_moved++;

}break;
case Qt::Key_Right:
if (current_square_x != maze_width - 1 && is_legal_move(current_square_y, current_square_x, current_square_y, current_square_x + 1)){

current_square_x++;

background_color_squares[current_square_y][current_square_x]->setBrush(start_and_path_background_color);
background_color_squares[previous_square_cord.first][previous_square_cord.second]->setBrush(maze_background_color);
previous_square_cord = {current_square_y, current_square_x};

square_moved++;

}break;

case Qt::Key_Left:
if (current_square_x != 0 && is_legal_move(current_square_y, current_square_x, current_square_y, current_square_x - 1)){

current_square_x--;

background_color_squares[current_square_y][current_square_x]->setBrush(start_and_path_background_color);
background_color_squares[previous_square_cord.first][previous_square_cord.second]->setBrush(maze_background_color);
previous_square_cord = {current_square_y, current_square_x};

square_moved++;
}break;
}
if (won_game()){
QMessageBox::about(this, "t", "You won!!!");
on_pushButton_3_clicked();
}
}


Added after 29 minutes:

Okay, so I figured out how to make it to work, I changed my widget focus to StrongFocus, but
I don't understand why this focusPolicy "setFocusPolicy" makes to work my Key_Up/Down/Left/Right, maybe someone could explain it, why
this code enables to work my arrow keys?



this->setFocusPolicy(Qt::StrongFocus);