1

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.

4

2 回答 2

7

尝试event handler机制。可能这些左右键事件已经在 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);)

于 2012-06-08T03:29:44.040 回答
0

我想添加更多内容,如果您想避免 QtWidgetTab 对象不切换选项卡,只需添加 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;
}

并且不要忘记添加 qApp->installEventFilter(this);

于 2014-07-17T14:04:59.297 回答