Evgenii Legotckoi
Evgenii LegotckoiMarch 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:

# 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, 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
ДЛ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:60points,
  • Rating points-1
СЦ

C ++ - Test 004. Pointers, Arrays and Loops

  • Result:50points,
  • Rating points-4
AT

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

  • Result:73points,
  • Rating points1
Last comments
J
JonnyJoMarch 30, 2023, 9:57 p.m.
Qt/C++ - Lesson 021. The drawing mouse in Qt Евгений, здравствуйте! Только начал изучение Qt и возник вопрос по 21ому уроку. После написания кода, выдаёт следующие ошибки В чём может быть проблема?
АН
Алексей НиколаевMarch 26, 2023, 7:10 p.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Добрый день, взял за основу ваш PopUp notification , и немного доработал его под свои нужды. Добавил в отдельном eventloop'e всплывающую очередь уведомлений с анимацией и таймеро…
АН
Алексей НиколаевMarch 26, 2023, 7:04 p.m.
Qt/C++ - Lesson 042. PopUp notification in the Gnome style using Qt Включите прозрачность в композит менеджере fly-admin-theme : fly-admin-theme ->Эффекты и всё заработает.
NSProject
NSProjectMarch 25, 2023, 12:35 a.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Да не я так к примеру просто написал.
Evgenii Legotckoi
Evgenii LegotckoiMarch 24, 2023, 8:09 p.m.
Django - Lesson 062. How to write a block-template tabbar tag like the blocktranslate tag Почитайте эту статью про "хлебные крошки"
Now discuss on the forum
BlinCT
BlinCTApril 1, 2023, 3:16 p.m.
Нужен совет по работе с ListView и несколькими моделями Спасибо, сейчас займусь этим.
NSProject
NSProjectMarch 31, 2023, 12:55 p.m.
Проверка комментария принадлежит он пользователю или нет DRF (Django Rest Framework) Здравствуйте! Сегодня я столкнулся с такой проблеммой. Существует модель комметариев. Где их соответственно достаточное количество. Все они выводятся при помощи запроса ajax (axios). Так ка…
P
PisychMarch 30, 2023, 12:50 p.m.
Как подсчитать количество по условию? Да! Вот так работает! Огромное Вам спасибо! ........
Evgenii Legotckoi
Evgenii LegotckoiMarch 29, 2023, 2:11 p.m.
Замена поля ManyToMany Картинки точно нужно хранить в медиа директории на сервере, а для обращения использовать ImageField. Который будет хранить только путь к изображению на сервере. Хранить изображения в базе данных…
ВА
Виталий АнисимовJan. 30, 2023, 2:17 a.m.
Как добавить виртуальную клавиатура с Т9 в своей проект на QML. Добрый день. Прошу помочь, пишу небольше приложение в Qt. Добвил в свой проект виртуальную клавиатуру от Qt. Но как добавить в него возможность изменения Т9 никак не могу понять.

Follow us in social networks