处理QT中的左右按键事件 [英] Handling left and right key events in QT

查看:728
本文介绍了处理QT中的左右按键事件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的一个QT窗口中有一个QTabWidget,它似乎吞没了左/右键事件.在主窗口中,我具有以下功能:

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";
}

当我按左右键以外的任何键时,处理程序将关闭,并将键码打印到控制台.当我按向左或向右时,它将移至选项卡小部件中的下一个左(或右)选项卡,并且VisionWindowkeyPressEvent方法从不触发.

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"; }
};

类似于主窗口,仅在按下左键或右键以外的其他键时才调用它.我还看到基于焦点所在的位置,有时向左或向右点击会将焦点切换到主窗口中的不同小部件,例如复选框.如果有什么方法可以回收左右键,或者我是否应该接受默认情况下QT中广泛使用的这些键并切换到其他方法?

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?

更新:

我最终在窗口构造函数中同时使用了#include <QApplication>qApp->installEventFilter(this);.缺点是选项卡小部件仍在切换选项卡. 这似乎成为Linux问题.从好的方面来说,我能够捕获所有关键事件.我的子小部件也吞没了其他键的事件,这解决了这个问题.

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.

推荐答案

尝试event handler机制.可能这些左键事件和右键事件已在Keypressevent之前处理过.

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

安装此事件过滤器.(qApplicationobject->installEventFilter(this);)

这篇关于处理QT中的左右按键事件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆