- 1. Project structure
- 2. main .py
- 3. Result
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:
- main .py
main .py
- from PyQt5 import QtWidgets
- from PyQt5.QtWidgets import QMainWindow, QLabel, QGridLayout, QWidget, QLineEdit
- from PyQt5.QtCore import QSize, QRegExp
- from PyQt5.QtGui import QRegExpValidator
- class MainWindow(QMainWindow):
- def __init__(self):
- 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("Введите IP-адрес", self), 0, 0)
- ipRange = "(?:[0-1]?[0-9]?[0-9]|2[0-4][0-9]|25[0-5])" # Part of the regular expression
- # Regulare expression
- ipRegex = QRegExp("^" + ipRange + "\\." + ipRange + "\\." + ipRange + "\\." + ipRange + "$")
- ipValidator = QRegExpValidator(ipRegex, self)
- lineEdit = QLineEdit()
- lineEdit.setValidator(ipValidator)
- grid_layout.addWidget(lineEdit, 0, 1)
- if __name__ == "__main__":
- import sys
- app = QtWidgets.QApplication(sys.argv)
- mw = MainWindow()
- mw.show()
- sys.exit(app.exec())
Result
The following result is obtained with the possibility validation window IP-address.