问题描述
首先,抱歉我的英语不好.
First, sorry for my bad English.
我正在尝试从用户那里获取 IP.我正在使用 QRegExpValidator 来检查用户输入.验证器成功阻止不需要的字符.但是我想知道当用户单击按钮时它是一个正确的 IP.当然我可以手动检查文本,但似乎有更好的方法,使用 QValidator 的状态枚举.QValidator.Acceptable 是我需要检查的.但我不知道如何使用它
I'm trying to get an IP from user. I'm using QRegExpValidator for checking user input. The validator blocks unwanted characters succesfully. But I want to learn it's a proper IP when user clicked the button. Of course I can check the text manually, but there seems a better way, using QValidator's state enum. QValidator.Acceptable is what I need to check. But I can't figure out how I can use it
这是我需要使用的:http://www.riverbankcomputing.co.uk/static/Docs/PyQt4/html/qvalidator.html#State-enum
这是我尝试过的(从主程序中提取的):
And here is what I tried(abstracted from main program):
from PyQt4 import QtCore, QtGui
from functools import partial
class Gui(QtGui.QDialog):
def __init__(self):
QtGui.QDialog.__init__(self)
editLayout=QtGui.QFormLayout()
edit=QtGui.QLineEdit()
edit.setMinimumWidth(125)
regex=QtCore.QRegExp("\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3}")
validator=QtGui.QRegExpValidator(regex, edit)
edit.setValidator(validator)
editLayout.addRow("Enter Client IP:", edit)
button=QtGui.QPushButton("Add Client")
button.clicked.connect(partial(self.addClientButtonClicked, edit, validator))
layout=QtGui.QVBoxLayout()
layout.addLayout(editLayout)
layout.addWidget(button)
self.setLayout(layout)
def addClientButtonClicked(self, edit, validator):
print("ip=", edit.text())
print(validator.State==QtGui.QValidator.Intermediate)
app=QtGui.QApplication([])
g=Gui()
g.show()
app.exec_()
所需的输出:
ip= 192.168.
False
ip= 192.168.2.1
True
但这就是我得到的:
ip= 192.168.
False
ip= 192.168.2.1
False
检查 QValidator 状态的正确方法是什么?
What is the proper way of checking QValidator's state?
推荐答案
你在这里没有做正确的事情.对比:
You're not doing the right thing here. The comparison:
validator.State==QtGui.QValidator.Intermediate
将枚举type与其值之一进行比较 - 这将总是False
!
Compares an enumeration type to one of its values - this will always be False
!
改用 validate
方法:
def addClientButtonClicked(self, edit, validator):
print("ip=", edit.text())
print(validator.validate(edit.text(), 0))
那么 192.168.2.1
的结果是:
('ip=', PyQt4.QtCore.QString(u'192.168.2.1'))
(2, 0)
validate
返回的元组的第一个元素是状态,您可以将其与 QValidator
的各种状态进行比较:
The first element of the tuple returned by validate
is the state, which you can compare to the various states of QValidator
:
def addClientButtonClicked(self, edit, validator):
state, pos = validator.validate(edit.text(), 0)
print(state == QtGui.QValidator.Acceptable)
为 192.168.2.1
这篇关于检查 QValidator 的状态的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!