Evgenii Legotckoi
March 15, 2017, 10:12 p.m.

PyQt5 - Lesson 005. Autocompletion for an input field using QCompleter

The Qt library has a QCompleter class, which allows you to offer autocompletion to the input word in the input fields. This class is also supported by the PyQt5 library.

In the minimum, the application of this class might look like this:

  1. # Create an input field
  2. lineEdit = QLineEdit(self)
  3. strList = ['Python', 'PyQt5', 'Qt', 'Django', 'QML'] # Create a list of words
  4. # We create QCompleter, in which we establish the list, and also the pointer to the parent
  5. completer = QCompleter(strList, lineEdit)
  6. lineEdit.setCompleter(completer) # Set QCompleter in the input field

For application in the program, this code can be implemented as follows:

  1. from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QLineEdit, QCompleter
  2. from PyQt5.QtCore import QSize
  3.  
  4.  
  5. class MainWindow(QMainWindow):
  6. # Override class constructor
  7. def __init__(self):
  8. # You must call the super class method
  9. QMainWindow.__init__(self)
  10.  
  11. self.setMinimumSize(QSize(480, 80)) # Set sizes
  12. self.setWindowTitle("Line Edit IP Address") # Set the window title
  13. central_widget = QWidget(self) # Create a central widget
  14. self.setCentralWidget(central_widget) # Install the central widget
  15.  
  16. grid_layout = QGridLayout(self) # Create QGridLayout
  17. central_widget.setLayout(grid_layout) # Set this accommodation in central widget
  18.  
  19. grid_layout.addWidget(QLabel("Autocompletion check", self), 0, 0)
  20.  
  21. # Create an input field
  22. lineEdit = QLineEdit(self)
  23. strList = ['Python', 'PyQt5', 'Qt', 'Django', 'QML'] # Create a list of words
  24. # We create QCompleter, in which we establish the list, and also the pointer to the parent
  25. completer = QCompleter(strList, lineEdit)
  26. lineEdit.setCompleter(completer) # Set QCompleter in the input field
  27. grid_layout.addWidget(lineEdit, 0, 1) # Add the input field to the grid
  28.  
  29.  
  30. if __name__ == "__main__":
  31. import sys
  32.  
  33. app = QApplication(sys.argv)
  34. mw = MainWindow()
  35. mw.show()
  36. sys.exit(app.exec())

Recommended articles on this topic

By article asked0question(s)

2

Do you like it? Share on social networks!

c
  • Dec. 18, 2017, 10:41 p.m.

Большое спасибо.
Вы очень мне помогли.

Evgenii Legotckoi
  • Dec. 19, 2017, 12:26 a.m.

Пожалуйста ))
Будут какие затруднения, задавайте вопросы на форуме в разделе PyQt5. PyQt5 не является моей рабочей нишей, но я работаю периодически с python, а сама библиотека Qt - это моё основное направление. Так что, если будет возможным, отвечу на вопросы или направлю, куда копать. Да и сообщество может поможет, ну и сами не стесняйтесь отвечать на вопросы других пользователей.

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • AK
    April 1, 2025, 11:41 a.m.
    Добрый день. В данный момент работаю над проектом, где необходимо выводить звук из программы в определенное аудиоустройство (колонки, наушники, виртуальный кабель и т.д). Пишу на Qt5.12.12 поско…
  • Evgenii Legotckoi
    March 9, 2025, 9:02 p.m.
    К сожалению, я этого подсказать не могу, поскольку у меня нет необходимости в обходе блокировок и т.д. Поэтому я и не задавался решением этой проблемы. Ну выглядит так, что вам действитель…
  • VP
    March 9, 2025, 4:14 p.m.
    Здравствуйте! Я устанавливал Qt6 из исходников а также Qt Creator по отдельности. Все компоненты, связанные с разработкой для Android, установлены. Кроме одного... Когда пытаюсь скомпилиров…
  • ИМ
    Nov. 22, 2024, 9:51 p.m.
    Добрый вечер Евгений! Я сделал себе авторизацию аналогичную вашей, все работает, кроме возврата к предидущей странице. Редеректит всегда на главную, хотя в логах сервера вижу запросы на правильн…
  • Evgenii Legotckoi
    Oct. 31, 2024, 11:37 p.m.
    Добрый день. Да, можно. Либо через такие же плагины, либо с постобработкой через python библиотеку Beautiful Soup