Jake
Jake

Reputation: 7783

Handling left and right key events in QT

I have a QTabWidget in one of my QT windows, and it seems to be swallowing the left/right key press events. In the main window I have the following function:

void VisionWindow::keyPressEvent(QKeyEvent* event) {
    std::cout << event->key() << "\n";
}

When I press any key other than left or right, the handler goes off and prints the key code to the console. When I press left or right, it moves to the next left (or right) tab in the tab widget, and the VisionWindow's keyPressEvent method never fires.

I tried to fix this with a subclass that would ignore the event:

class KeylessTabWidget : public QTabWidget {
    public:
        KeylessTabWidget(QWidget* parent) : QTabWidget(parent) {}
        void keyPressEvent(QKeyEvent* event) { event->ignore(); std::cout << "ignored an event\n"; }
};

Similar to the main window, this is only called when keys other than left or right are pressed. I'm also seeing that based on where the focus is, sometimes hitting left or right will switch the focus to different widgets in the main window, like checkboxes. If there any way to reclaim the left and right keys, or should I just accept that these are widely used in QT by default and switch to something else?

Update:

I ended up using #include <QApplication> along with qApp->installEventFilter(this); in my window constructor. The downside is that the tab widget is still switching tabs. This seems to be a linux issue. On the plus side, I'm able to capture all key events. I was having events get swallowed by child widgets for other keys as well, and this solved it.

Upvotes: 1

Views: 7941

Answers (2)

Alexandre M.
Alexandre M.

Reputation: 75

I would like to add something more, if you want to avoid the QtWidgetTab object to not switch tabs, just add return true :

bool MyObject::eventFilter(QObject *object, QEvent *ev)
{
 if (e->type() == QEvent::KeyPress)
  {
       QKeyEvent *keyEvent = static_cast<QKeyEvent *>(ev);
       qDebug() << keyEvent->key() ;

      return true; //Here the signal was processed and is not going to be handled by QtTabWidget 
  }

 return false;
}

And don't forget to add qApp->installEventFilter(this);

Upvotes: 0

ScarCode
ScarCode

Reputation: 3094

Try event handler mechanism.May be these left and right key events are already handled ahead of Keypressevent.

bool MainWindow::eventFilter(QObject *object, QEvent *e)
{
 if (e->type() == QEvent::KeyPress)
  {
  QKeyEvent *keyEvent = static_cast<QKeyEvent *>(e);
  std::cout << event->key() << "\n";
  }
 return false;
}

Install this eventfilter.(qApplicationobject->installEventFilter(this);)

Upvotes: 7

Related Questions