Important: Please read the Qt Code of Conduct -

Arrows Key order in grid layout

  • I have created 10 push buttons on my application and set them as grid layout, 5 rows and 2 columns.
    When I run my application and using the arrows for navigation between the buttons, I get unclear focus movment.
    My expectation is to:

    • Get the upper button when I go up.
    • Get the left button when I go left.

    But instead the focus move not alwayes to the directation that I want it to go.
    What am I missing?

    Best regards,

  • Moderators

    @IL said:

    What am I missing?

    sorry, but who should be able to answer this question when you don't post a single line of code?!

  • Hi,
    The question is theory and very simple.
    What is the focus or navigation policy when using grid layout?
    Is there vertical movement or horizontal movement in grid layout.
    because I get something between.


  • Moderators

    ok now i got you.
    This is what happens:

    1. keyPressEvent() handler of the button (QAbstractButton) catches the up/left and down/right keys
    2. then it calls focusNextPrevChild() on it's parent widget
    3. the default implementation takes the current focus widget and focuses the next widget in the child list

    So the order is given by the order you added the child widget (buttons) to the parent widget.

    So to achieve what you want you would either need subclass your buttons (or install an eventfilter on them) and catch the up/down/right/left keys and focus the next button by yourself.

    Call QLayout::indexOf() and use QGridLayout::getItemPosition() to get the row and column of the current focused widget and determine which item to focus next.

  • @raven-worx
    Thanks for the clarification,
    Can you give more details about what is event filter installation?

  • Moderators

    here ya go