Evgenii Legotckoi
Evgenii LegotckoiMarch 15, 2017, 12: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:

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

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

from PyQt5.QtWidgets import QApplication, QMainWindow, QLabel, QGridLayout, QWidget, QLineEdit, QCompleter
from PyQt5.QtCore import QSize


class MainWindow(QMainWindow):
    # Override class constructor
    def __init__(self):
        # You must call the super class method
        QMainWindow.__init__(self)

        self.setMinimumSize(QSize(480, 80))         # Set sizes 
        self.setWindowTitle("Line Edit IP Address") # Set the window title
        central_widget = QWidget(self)              # Create a central widget
        self.setCentralWidget(central_widget)       # Install the central widget

        grid_layout = QGridLayout(self)         # Create QGridLayout
        central_widget.setLayout(grid_layout)   # Set this accommodation in central widget

        grid_layout.addWidget(QLabel("Autocompletion check", self), 0, 0)

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


if __name__ == "__main__":
    import sys

    app = QApplication(sys.argv)
    mw = MainWindow()
    mw.show()
    sys.exit(app.exec())
We recommend hosting TIMEWEB
We recommend hosting TIMEWEB
Stable hosting, on which the social network EVILEG is located. For projects on Django we recommend VDS hosting.

Do you like it? Share on social networks!

c
  • Dec. 18, 2017, 11:41 a.m.

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

Evgenii Legotckoi
  • Dec. 18, 2017, 1:26 p.m.

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

Comments

Only authorized users can post comments.
Please, Log in or Sign up
e
  • ehot
  • April 1, 2024, 12:29 a.m.

C++ - Тест 003. Условия и циклы

  • Result:78points,
  • Rating points2
B

C++ - Test 002. Constants

  • Result:16points,
  • Rating points-10
B

C++ - Test 001. The first program and data types

  • Result:46points,
  • Rating points-6
Last comments
k
kmssrFeb. 9, 2024, 5:43 a.m.
Qt Linux - Lesson 001. Autorun Qt application under Linux как сделать автозапуск для флэтпака, который не даёт создавать файлы в ~/.config - вот это вопрос ))
Qt WinAPI - Lesson 007. Working with ICMP Ping in Qt Без строки #include <QRegularExpressionValidator> в заголовочном файле не работает валидатор.
EVA
EVADec. 25, 2023, 9:30 p.m.
Boost - static linking in CMake project under Windows Ошибка LNK1104 часто возникает, когда компоновщик не может найти или открыть файл библиотеки. В вашем случае, это файл libboost_locale-vc142-mt-gd-x64-1_74.lib из библиотеки Boost для C+…
J
JonnyJoDec. 25, 2023, 7:38 p.m.
Boost - static linking in CMake project under Windows Сделал всё по-как у вас, но выдаёт ошибку [build] LINK : fatal error LNK1104: не удается открыть файл "libboost_locale-vc142-mt-gd-x64-1_74.lib" Хоть убей, не могу понять в чём дел…
G
GvozdikDec. 19, 2023, 8:01 a.m.
Qt/C++ - Lesson 056. Connecting the Boost library in Qt for MinGW and MSVC compilers Для решения твой проблемы добавь в файл .pro строчку "LIBS += -lws2_32" она решит проблему , лично мне помогло.
Now discuss on the forum
DA
Dr Gangil AcademicsApril 20, 2024, 5:45 p.m.
Unlock Your Aesthetic Potential: Explore MSC in Facial Aesthetics and Cosmetology in India Embark on a transformative journey with an msc in facial aesthetics and cosmetology in india . Delve into the intricate world of beauty and rejuvenation, guided by expert faculty and …
a
a_vlasovApril 14, 2024, 4:41 p.m.
Мобильное приложение на C++Qt и бэкенд к нему на Django Rest Framework Евгений, добрый день! Такой вопрос. Верно ли следующее утверждение: Любое Android-приложение, написанное на Java/Kotlin чисто теоретически (пусть и с большими трудностями) можно написать и на C+…
Павел Дорофеев
Павел ДорофеевApril 14, 2024, 12:35 p.m.
QTableWidget с 2 заголовками Вот тут есть кастомный QTableView с многорядностью проект поддерживается, обращайтесь
f
fastrexApril 4, 2024, 2:47 p.m.
Вернуть старое поведение QComboBox, не менять индекс при resetModel Добрый день! У нас много проектов в которых используется QComboBox, в версии 5.5.1, когда модель испускает сигнал resetModel, currentIndex не менялся. В версии 5.15 при resetModel происходит try…

Follow us in social networks