How Best to Prevent Focus Leaving a Widget?

  • I have a need within a given Qt window (main and dock) to validate data that has been entered in a field-type widget (QLineEdit typically), and not allow the keyboard focus to move to a different widget in the same window when the data is invalid. There are informational events for the widgets involved in the focus transfer, but not a way to directly block the focus out (event).

    Does anyone have a suggestion for what the best way to do this is?

  • Lifetime Qt Champion


    In that case shouldn't you use a modal QDialog to ensure your user can't do anything you don't want while the input is wrong ?

  • I suggest exploring alternatives also:

    • Mark fields with invalid values and disable "apply" "ok" and similar controls until all invalid values are corrected

    • Revert to the last known good value if the user leaves a field with an invalid value in it

    • Prevent entering an invalid value by restricting what users can type

  • Moderators

    You could go and set all other widgets to disabled

    void QWidget::setDisabled(bool disable)

    convenient enough, if you have a good Layouttree

Log in to reply