Handling left and right key events in QT

半世苍凉 提交于 2019-12-08 04:33:16

问题


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.


回答1:


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);)




回答2:


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);



来源:https://stackoverflow.com/questions/10942384/handling-left-and-right-key-events-in-qt

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!