Evgenii Legotckoi
Nov. 12, 2016, 6:39 p.m.

PyQt5 - Lesson 001. QLineEdit IP Address

Available articles on Qt/С++ and Qt/QML

When developing network applications may need to create molds for input ip-address, but the use of a simple method setInputMask ( "000.000.000.000; _"); According to the argument for QLineEdit does not provide the proper result as the mask allows you to enter the values of 999, 657, etc., while the IP-address of the limited number of 255.

One way to solve this problem is to use Validator.

This lesson has been implemented in the Qt / C ++, and now the same thing to realize PyQt5/Python.


Project structure

The project will consist of only one file:

  1. main .py

main .py

  1. from PyQt5 import QtWidgets
  2. from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QLineEdit
  3. from PyQt5.QtCore import QSize, QRegExp
  4. from PyQt5.QtGui import QRegExpValidator
  5.  
  6.  
  7. class MainWindow(QMainWindow):
  8.  
  9. def __init__(self):
  10. QMainWindow.__init__(self)
  11.  
  12. self.setMinimumSize(QSize(480, 80)) # Set sizes
  13. self.setWindowTitle("Line Edit IP Address") # Set the window title
  14. central_widget = QWidget(self) # Create a central widget
  15. self.setCentralWidget(central_widget) # Install the central widget
  16.  
  17. grid_layout = QGridLayout(self) # Create QGridLayout
  18. central_widget.setLayout(grid_layout) # Set this accommodation in central widget
  19.  
  20. grid_layout.addWidget(QLabel("Введите IP-адрес", self), 0, 0)
  21.  
  22. ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # Part of the regular expression
  23. # Regulare expression
  24. ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$")
  25. ipValidator = QRegExpValidator(ipRegex, self)
  26.  
  27. lineEdit = QLineEdit()
  28. lineEdit.setValidator(ipValidator)
  29. grid_layout.addWidget(lineEdit, 0, 1)
  30.  
  31.  
  32. if __name__ == "__main__":
  33. import sys
  34.  
  35. app = QtWidgets.QApplication(sys.argv)
  36. mw = MainWindow()
  37. mw.show()
  38. sys.exit(app.exec())

Result

The following result is obtained with the possibility validation window IP-address.

Link to repository

Do you like it? Share on social networks!

Comments

Only authorized users can post comments.
Please, Log in or Sign up
  • Last comments
  • 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
  • A
    Oct. 19, 2024, 5:19 p.m.
    Подскажите как это запустить? Я не шарю в программировании и кодинге. Скачал и установаил Qt, но куча ошибок выдается и не запустить. А очень надо fb3 переконвертировать в html