void MyWidget::keyPressEvent(QKeyEvent *event) { if (event->key() == Qt::Key_Enter) { // do something when Enter key is pressed } }
if (event->modifiers() & Qt::ControlModifier) { // do something when Control key is pressed }
QKeyEvent event(QKeyEvent::KeyPress, Qt::Key_Escape, Qt::NoModifier); QApplication::sendEvent(this, &event);This code example demonstrates how to programmatically generate a key event using the QKeyEvent class. The constructor is used to specify the event type (KeyPress), the key that was pressed (Escape), and the key modifiers (NoModifier). The sendEvent() function is called to send the event to a specified object. In this example, the event is sent to the current widget using the 'this' pointer.