TextEdit and eventFilter: characters not appearing on ui element
Solved
General and Desktop
-
Hi everyone.
I have a
textEdit
widget on mymainwindow.ui
, and I would like to catch the key pressed by the user when the focus is on thetextEdit
.
I gave a read here and adapted the example to this:mainwindow.h
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QMainWindow> namespace Ui { class MainWindow; } class MainWindow : public QMainWindow { Q_OBJECT public: explicit MainWindow(QWidget *parent = nullptr); ~MainWindow(); private: Ui::MainWindow *ui; protected: bool eventFilter(QObject *obj, QEvent *ev) override; }; #endif // MAINWINDOW_H
mainwindow.cpp
#include "mainwindow.h" #include "ui_mainwindow.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); ui->textEdit->setFocus(); ui->textEdit->installEventFilter(this); } MainWindow::~MainWindow() { delete ui; } bool MainWindow::eventFilter(QObject *obj, QEvent *event) { // if (obj == textEdit) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); qDebug() << "Ate key press " << keyEvent->text(); return true; } else { return false; } // } else { // // pass the event on to the parent class // return QMainWindow::eventFilter(obj, event); // } }
mainwindow.ui
<?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>MainWindow</class> <widget class="QMainWindow" name="MainWindow"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>400</width> <height>300</height> </rect> </property> <property name="windowTitle"> <string>MainWindow</string> </property> <widget class="QWidget" name="centralWidget"> <widget class="QTextEdit" name="textEdit"> <property name="geometry"> <rect> <x>100</x> <y>50</y> <width>221</width> <height>141</height> </rect> </property> </widget> </widget> <widget class="QMenuBar" name="menuBar"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>400</width> <height>25</height> </rect> </property> </widget> <widget class="QToolBar" name="mainToolBar"> <attribute name="toolBarArea"> <enum>TopToolBarArea</enum> </attribute> <attribute name="toolBarBreak"> <bool>false</bool> </attribute> </widget> <widget class="QStatusBar" name="statusBar"/> </widget> <layoutdefault spacing="6" margin="11"/> <resources/> <connections/> </ui>
The keys pressed are shown correctly on the output, but they do not appear on my
textEdit
.How can I solve this?
-
Hi,
Because you are stoping the event processing there by returning true exactly how it is explained in the documentation you are linking.
-
@SGaist
Hi. Ok, I changedeventFilter()
a little bit:bool MainWindow::eventFilter(QObject *obj, QEvent *event) { if (obj == ui->textEdit) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent*>(event); qDebug() << "Ate key press " << keyEvent->text(); } } return QMainWindow::eventFilter(obj, event); }
and now it works. Thanks!
-