Qt::Key is not being recognized by keypressevent()
-
Hi!!..
I do have an strange issue regarding to key detection inside the keyPressEvent() function.
I have 5 form classes which two of them contains keyPressEvent() function, the first one is inherited by QMainWindow and the other one from QDialog.
All the keys to be used as input inside keyPressEvent() work as expected in the QMainWindow form,
I copy-pasted the same keyPressEvent function from QMainWindow derived class into QDialog derived class, but in this second one only key being read is Qt::Key_Return, this is so weird since the definition of both keyPressEvent are the same...What do 'm missing?
This is what I have in both main window and dialog forms (corresponding to their class names):
void wmaster::keyPressEvent(QKeyEvent* _e){ if (!debug) return; static ushort i = 0; //vQWidgets is a std vector containing all widgets used in this window if (i >= vQWidgets.size()) i = 0; QWidget*& debug_obj = vQWidgets[i]; if (!debug_obj) return; const QRect r = debug_obj->geometry(); switch (_e->key()){ case Qt::Key_W: //this gets read only in QMainWindow derived class debug_obj->move(r.x(), r.y() - 10); break; case Qt::Key_S: //this gets read only in QMainWindow derived class debug_obj->move(r.x() - 10, r.y()); break; case Qt::Key_A: //this gets read only in QMainWindow derived class debug_obj->move(r.x(), r.y() + 10); break; case Qt::Key_D: //this gets read only in QMainWindow derived class debug_obj->move(r.x() + 10, r.y()); break; //print geometry (this is being read in both classes) case Qt::Key_Return: QMessageBox::information(nullptr, "DEBUG GEOMETRY", "Position\t\t " + QString::number(r.x()) + " : " + QString::number(r.y()) + "\nDim\t\t " + QString::number(debug_obj->size().width()) + " : " + QString::number(debug_obj->size().height())); break; //do target next qwidget in vQWidgets to be controlled //this only works with QMainwindow derived class case Qt::Key_N: ++i; break; } }
Resuming, in the second form class, only Key_Return is being read... the rest of the keys are just being skipped..
-
Hi,
Since you are doing the same stuff, why not implement an event filter and install it on both widgets ? That will save you the trouble of copy pasting code and keeping the implementation in sync.
-
@U7Development
Do as @SGaist suggests.But as to why the difference:
QDialog
has its ownkeyPressEvent
override, that handles keys differently from in a main window. If you Googleqdialog keypressevent
you will see this discussed.