qtpyqtqcompleterqmodelindex

Pass QModelIndex instead of QString when QCompleter highlighted


There is a QCompleter (set to QLineEdit) populated with QStandardItemModel. That model also populates the QTableView, I need to get the QModelIndex and select it in QTableView but it fails, it passes text instead of QModelIndex:

completer.highlighted.connect(print_index) 

passes only the first index:

completer.highlighted.connect(lambda : select_index(completer.currentIndex()))

def select_index(index):

    table_view.setCurrentIndex(index)

I read docs, but cannot understand what do I do wrong. http://doc.qt.io/qt-5/qcompleter.html#highlighted-1


Solution

  • There's two versions of the highlighted signal: the default one emits a string, the other emits a QModelIndex To get the index, use:

    completer.highlighted[QtCore.QModelIndex].connect(onHighlight)
    

    But be careful, this is the index in the completion model, not the model you populated the completer with. You can use mapToSource to get the original index.

    def onHighLight(index):
        #completer model
        print(index)
        #model 
        sourceIndex=completer.completionModel().mapToSource(index)
        print(sourceIndex)