pythonpyqtpyqt5qcompleter

Qcompleter currentCompletion does not work


Recently, I am working on a code completion demo. I want to create a tooltip association with items in the popup(). The tooltip shows some information queried by the item that it is associated with when users select one item in the popup listview. I tried currentCompletion() to get the item content, it only returned the first completion for one time. How to fix this?

Here is my application

from PyQt5.QtCore import *
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *


def get_data(model):
# Searching through the Doc
# Result shows in a dictionary structure
    result = {"alpha": 0, "apple": 1, "agree": 2}
    icon_address = ['..\..\Src\Img\A.png', '..\..\Src\Img\E.png','..\..\Src\Img\O.png']
    for cmd, value in result.items():
        item = QStandardItem(cmd)
        item.setIcon(QIcon(icon_address[value]))
        model.insertRow(0, item)


class CodeAC:

   def __init__(self, input_line):
      self.completer = QCompleter()
      input_line.setCompleter(self.completer)
      self.model = QStandardItemModel()

   def active_script(self):
      get_data(self.model)
      self.completer.setModel(self.model)

   def tip_balloon(self):
      key = self.completer.currentRow()
      print(key)

Here is my Main:

from Src.Extention.src.code_ac import *
import sys
import ctypes

class MainWindow(QWidget):

    def __init__(self):
        super(MainWindow, self).__init__()
        self.extention = None
        self.entry = QLineEdit(self)

    def init_main(self):
        self.setGeometry(600,600,800,600)
        self.setWindowTitle('VISA Communication')
        self.setWindowIcon(QIcon('..\..\Src\Img\icon.png'))
        self.show()

    def active_extention(self):
        self.extention = CodeAC(self.entry)
        self.extention.active_script()

if __name__ == '__main__':

   app = QApplication(sys.argv)
   root = MainWindow()
   root.init_main()
   root.active_extention()
   sys.exit(app.exec_())

Print only give 0, even I select the second completion. Here is the screen shoot


Solution

  • You must use activated signal of QCompleter and modify the tip_balloon:

    [...]
       self.completer.setModel(self.model)
       self.completer.activated.connect(self.tip_balloon)
    
    def tip_balloon(self, text):
       print(text)