由于QT没有提供现成的IP地址控件,而仅仅使用正则表达式和inputMask为QLineEdit进行IP地址输入限制和验证,效果不怎么理想。由于项目需要,所以用PyQt4封装了一个IPv4地址控件。
参考地址:http://www.cppblog.com/cctoqh/archive/2011/06/03/148018.html,该文章是用C++实现的。
源代码如下:
from PyQt4.QtGui import *
from PyQt4.QtCore import *
class IpPartEdit(QLineEdit):
def __init__(self, parent = None):
QLineEdit.__init__(self, parent)
self.nextTab = None
self.setMaxLength(3)
self.setFrame(False)
self.setAlignment(Qt.AlignCenter)
validator = QIntValidator(0, 255, self)
self.setValidator(validator)
self.connect(self, SIGNAL('textEdited(QString)'),\
self, SLOT('text_edited(QString)'))
def set_nextTabEdit(self, nextTab):
self.nextTab = nextTab
def focusInEvent(self, event):
self.selectAll()
super(IpPartEdit, self).focusInEvent(event)
def keyPressEvent(self, event):
if (event.key() == Qt.Key_Period):
if self.nextTab:
self.nextTab.setFocus()
self.nextTab.selectAll()
super(IpPartEdit, self).keyPressEvent(event)
@pyqtSlot('QString')
def text_edited(self, text):
validator = QIntValidator(0, 255, self)
ipaddr = text
pos = 0