Unsolved How to handle key press in a QDialog?
-
QDialog has its own Event http://doc.qt.io/qt-4.8/qdialog.html#keyPressEvent
-
Hi,
Out of curiosity, what do you mean exactly by " handle key press from the buttons" ?
-
Originally, I thought that QPushButton is the class that receives the key event. In other words, the QPushButton know if it was clicked by the mouse or the enter key was pressed. But it turned out that MainWindow and QDialog intercept the key event.
-
It depends whether the button has focus or not.
-
Do you mean that the
keyPressEvent(QKeyEvent * event)
can be in a QPushButton subclass?
Why do MainWindow and QDialog handle key events too?
-
Because the widget who has the focus handles the events.
-
Alright, Let's say a search dialog has a line edit and a button for simplicity. If the line edit is in focus and the enter key is pressed, the line edit's keyPressEvent(QKeyEvent * event) will be called. And if I tab to select the button and press the enter key, the button's keyPressEvent(QKeyEvent * event) will be called.
Is there a standard way in Qt to avoid duplicate code for this situation?
-
Can you explain what exactly you are trying to achieve ?
-
I'm trying to search for users in a database using a QDialog. The QDialog has 3 QLineEdit (one for first name, middle and last name). 2 QPushButton (Search and cancel).
Now when search qdialog is in focus, it should receive the key event. But the behavior I want is, as soon as the user enters at least the first name, he can press the enter key (while the first name line edit is in focus) and all matches of the first name will be displayed. Or the user can enter either the middle or last name in combination with the first name. The user can also tab to the search button and press enter to search or tab to the cancel button and press the enter key to close the search dialog.
So basically:
- The qdialog (the search dialog) will be in focus
- The user can press enter from any of 3 QLineEdit while in focus
- The user can press enter while the search button is in focus
- The user can press enter while the cancel button is in focus
2 and 3 will cause the info provided by the user to compare against what is in the database for a match. How should I avoid the duplicate code in four widgets?
-
What about using the QLineEdit::returnPressed signal ?