Prevent QKeyEvent from propagating to parent widget (QDialog)

  • I have a QDialog which creates another QDialog, and when I hit Esc key both QDialogs close. I tried everything in the event handler of the child QDialog to prevent the parent QDialog from closing (though I need it to close when it receives Esc directly). Nothing works. I even tried destroying the QKeyEvent object itself in the child event handler. It just gives me a SegFault

    I can work around this issue by checking whether the Esc key was pressed in the child QDialog but it doesn't look like a nice way of preventing the parent QDialog from closing

    Is there a way to fix this issue without using some ugly workarounds?

  • @deisik
    Pressing Escape in one dialog should not be closing a second dialog. And there is no reason to be doing any key event stuff. Show your code which exhibits the behaviour.

  • Child QDialog:

    void Child::keyReleaseEvent(QKeyEvent *event) {
    if (Qt::Key(event->key()) == Qt::Key_Escape)

    Parent QDialog:

    void Parent::keyReleaseEvent(QKeyEvent *event) {
    if (event->key() == Qt::Key_Escape)
    	emit close();

    Child QDialog is called using exec()

  • @deisik
    But why are you doing any of this? Escape closes a dialog anyway, why all the code? Why not have no code??

    As for the reason: I assume acting on a key press in one dialog and a key release in another is a bit "odd". I guess the child gets the press, closes, and then its the parent which sees the key release and so closes?

    I think your code keeps changing...?

  • I was trying different combinations (release vs press). Neither works. Now changed everything to keyReleaseEvent. Didn't change anything

  • @deisik
    Before we spend time trying to fathom this: Why do you have any code at all? Without any code, doesn't Escape do just what you want?

  • I double checked everything, no more keyPressEvents. The code is exactly as above. Now I'm trying to remove the handlers completely

  • Well, I removed both handlers and it finally started to work as intended. The reason why I used them in the first place was to fix the problem somehow which showed up somewhere else (maybe it was not even related)

    Anyway, I think I can mark this topic as solved

Log in to reply