[Python] Using PyQt6 and a QListView, backed by a QAbstractListModel, setCurrentIndex and...

Discussão em 'Python' iniciado por Stack, Março 11, 2025.

  1. Stack

    Stack Membro Participativo

    In my PyQt6 application, there is a situation where I am updating the underlying QAbstractListModel for a QListView. After the update, I'm trying to select a specific index. The QListView has self.setSelectionMode(QAbstractItemView.SelectionMode.SingleSelection) in its constructor.

    This is the code that's called after a model update.

    idx = self._media_browser.get_file_index(self.current_file)
    q_idx = self._media_browser.model().createIndex(idx, 0)
    if not q_idx.isValid():
    self.log.error('Index is invalid')
    self._media_browser.scrollTo(q_idx)
    self._media_browser.setCurrentIndex(q_idx)


    self.current_file stores the file name of the item I want to select. I never get the Index is invalid message in my logs. I've tried to remove the scrollTo and change the order of it and the setting of the Index. Sometimes, the correct file will get selected. Sometimes it won't. It's completely arbitrary. I've tried adding a QApplication.processEvents() before calling this and it doesn't make a difference. I've also tried wrapping the logic in a QTimer.singleShot(100... and that didn't improve the reliability either.

    The exact revision and location of where I've placed this function can be found here:

    https://gitlab.com/djsumdog/mediahu...3b7b1b4ff/mediahug/gui/viewtab/viewtab.py#L73

    The get_file_index() looks like the following:

    def get_file_index(self, filename: str) -> Optional[int]:
    for i, file in enumerate(self.all_files()):
    if file['filename'] == filename:
    return i


    I'm guessing this is some kind of race condition. Is there a way to wait and ensure the QListView is ready to select/scroll to the given index? The index is valid, but sometimes the setCurrentIndex selects the correct item and sometimes it does not.

    Continue reading...

Compartilhe esta Página