Important: Please read the Qt Code of Conduct -

How to set keyboard focus to a QListWidgetItem?

  • So I wrote a mobile car player in C++ using Qt5. The program mainly consists of a QListWidget. You click on a song and it plays. The song that is currently playing should always be selected automatically.

    So far everything works great - the QListWidget is set to only have one item selected at once. Now if you play a song and the song ended, the next one in the list gets selected automatically. This works as intended, too (using setSelected() on QListWidgetItem). However, once the selected item gets changed programatically, there is still a keyboard focus set on the item which has been clicked previously. I can see this by moving up and down using the arrow keys on my keyboard - there's also a thin blue line under the QListWidgetItem which currently has the keyboard focus.

    Usually, there is a setFocus() function for each widget, but since QListWIdgetItems are no widgets (which makes sense), there is only a setFocus() function for the QListWidget - but it can't set the keyboard focus to a specific item.

    Is there any way to manipulate the keyboard focus?

  • Lifetime Qt Champion

    HI and welcome
    Did you try
    and set
    setCurrentRow(int row)
    maybe with
    row(const QListWidgetItem *item)

    if you already have the QListWidgetItem

  • @mrjj Wow thank you - that did the trick :)

Log in to reply