0

I have a QT Application on Windows which has a mode of using arrow keys, and also a mode which should totally ignore these arrow keys. That is, I want the arrow keys to not to trigger any event once the user checks a box.

I saw a post where eventFilter() was suggested, but I did not get how I could use it. Here is the checkbox event that listens the user, and gets triggered once the user checks it. In the else part I want the eventFilter() to work for arrow keys, but so far I could not get it running.

void MainWindow::on_checkBoxSmartCutMode_stateChanged(int arg1)
{
    if (arg1 == 0)
    {
     // do as usual, arrow keys should work
    }
    else
    {
        eventFilter(); // if any arrow key is pressed, ignore the event
    }

}

Any suggestions?

Schütze
  • 1,044
  • 5
  • 28
  • 48
  • There is a basic version [here](https://stackoverflow.com/a/26976984/3484570). You just need to change it to use arrow keys and check the checkbox state. Although you could just directly do `if (checkbox.isChecked()) return;` in your arrow key handler. – nwp Nov 20 '17 at 09:39

1 Answers1

1

You can use keyEvent as your key filter by override keyPressEvent and test your checkbox state.

example:

void MainWindow::keyPressEvent(QKeyEvent *event)
{
    // check your checkbox state
    if (ui->poCheckBox->checkState() == Qt::Unchecked)
       // do as usual, arrow keys should work
       return;

    switch(event->key())
    {
      case Qt::Key_Left:
      case Qt::Key_Right: // add more cases as needed
        event->ignore(); // if any arrow key is pressed, ignore the event
        return;
    }

    // handle the event
}
Simon
  • 1,522
  • 2
  • 12
  • 24
  • This makes a lot of sense. I'll accept this answer. Can you also tell me how I can access to `ui` from another class which takes care of the key events? – Schütze Nov 20 '17 at 11:47
  • what is the reason you want to access the UI from other class? communicate between classes simple use Qt signle/slot. – Simon Nov 20 '17 at 11:58
  • I have a class that takes care of arrow key events, and another class where I make necessary calculations and decide what happens. I don't want everything to be in the same class. – Schütze Nov 20 '17 at 12:04
  • 1
    In your UI class create signal with `stateChanged(bool)` and in the handler class keep private boolean member for the key lock state. and update this member with proper slot connected to the UI signal. – Simon Nov 20 '17 at 13:07