mic*_*elh 3 python validation input pyqt5
这是一个关于输入验证的两部分问题,其中包含一个特定的组件和另一个更通用的组件。
具体的:
虽然研究的话题,我发现这对正则表达式。我意识到这篇文章中的代码正在使用PyQt4。但是我想让它与PyQt5一起工作,因为我已经用它开始了我的项目。(显然是盲目的-我只能为此找到C ++文档)
这是我尝试的:
# somewhere above:     
self.le_input = QtWidgets.QLineEdit()
# at some point validate_input gets called:
# more on that in the second part of this question
def validate_input(self):
    reg_ex = QtCore.QRegExp(""[0-9]+.?[0-9]{,2}"")
    input_validator = QtGui.QRegExpValidator(reg_ex, self.le_input.text())
    self.le_input.setValidator(input_validator)
当我运行代码时,出现以下错误:
QRegExpValidator(父:QObject =无):参数1具有意外类型'QRegExp'QRegExpValidator(QRegExp,父:QObject =无):参数2具有意外类型'str'
这些不是必需的参数吗?有谁知道如何使它工作?
一般:
在Python中使用PyQt实现实时验证的有效方法是什么?
目前,我将使用:
self.le_input.textChanged.connect(self.validate_input)
确实可以,但是一旦我尝试将两个相互影响的QtLineEdits连接到同一个插槽,事情就停止了,因为两个人同时调用了“ textChanged”。
用例:两个输入字段:Amount before TAX和Amount after TAX-以及您输入的任何内容都会在键入时自动填充另一个字段   。
首先进行验证,然后进行计算,然后输出到其他字段。
提前谢谢了!任何帮助深表感谢!
您可以为不同的QLineEdit对象设置不同的验证器。
QRegExpValidator 有两个构造函数:
QRegExpValidator(parent: QObject = None)
QRegExpValidator(QRegExp, parent: QObject = None)
因此,您应该将代码更改为:
reg_ex = QRegExp("[0-9]+.?[0-9]{,2}")
input_validator = QRegExpValidator(reg_ex, self.le_input)
self.le_input.setValidator(input_validator)
为QLineEdit设置验证器后,就无需使用
self.le_input.textChanged.connect(self.validate_input)
只需删除它。那应该工作正常。
如果要查找有关PyQt5的文档,可以在控制台中简单地使用它:
pydoc3 PyQt5.QtGui.QRegExpValidator
但是pydoc只能显示很少的信息,因此您也应该使用C ++版本的文件。
最后,有关此的示例:
from PyQt5.Qt import QApplication
from PyQt5.QtCore import QRegExp
from PyQt5.QtGui import QRegExpValidator
from PyQt5.QtWidgets import QWidget, QLineEdit
import sys
class MyWidget(QWidget):
    def __init__(self, parent=None):
        super(QWidget, self).__init__(parent)
        self.le_input = QLineEdit(self)
        reg_ex = QRegExp("[0-9]+.?[0-9]{,2}")
        input_validator = QRegExpValidator(reg_ex, self.le_input)
        self.le_input.setValidator(input_validator)
if __name__ == '__main__':
    a = QApplication(sys.argv)
    w = MyWidget()
    w.show()
    a.exec()