我有一个带有QIntValidator:的Line Edit小部件
number_textbox = QLineEdit()
number_textbox.setText("0")
number_textbox.setValidator(QIntValidator())
此外,我将文本框的旧值存储在dict:中
old_val[uid_key] = 0
当文本框为空时,如果用户点击框外或按下回车键,我希望能够将文本框中的文本替换为旧值:
number_textbox.editingFinished.connect(lambda: self.editing_finished_function(number_textbox, old_val[uid_key]))
def editing_finished_function(self, textbox, old_val):
if textbox.text() == '':
textbox.setText(old_val)
else:
old_val = textbox.text()
不幸的是,QIntValidator((似乎认为空值无效,并且从未启动我的函数。有办法做我在这里找的事吗?
来自文档:
void QLineEdit::editingFinished((
按下Return或Enter键或行编辑失去焦点时会发出此信号。请注意,如果在edit行上设置了validator((或inputMask((,并按下回车/回车键,则只有当输入遵循inputMask(并且validator(((返回QValidator::Acceptable时,才会发出editingFinished((信号。
并且QIntValidator似乎不认为空字符串是有效的。因此,我建议您使用QRegExpValidator
创建自己的验证器
下面是同时接受数字和空字符串的验证器
regexp = QtCore.QRegExp('(^[0-9]+$|^$)')
validator = QtGui.QRegExpValidator(regexp)
完整示例:
import sys
from PyQt5 import QtWidgets, QtGui, QtCore
class MainWidget(QtWidgets.QWidget):
old_val = {'val': '0'}
def __init__(self):
super(MainWidget, self).__init__()
self.setLayout(QtWidgets.QVBoxLayout())
self.setFocusPolicy(QtCore.Qt.ClickFocus)
regexp = QtCore.QRegExp('(^[0-9]+$|^$)')
validator = QtGui.QRegExpValidator(regexp)
number_textbox = QtWidgets.QLineEdit()
number_textbox.setText(self.old_val['val'])
number_textbox.setValidator(validator)
number_textbox.editingFinished.connect(lambda: self.editing_finished_function(number_textbox))
self.layout().addWidget(number_textbox)
def editing_finished_function(self, textbox):
print("FINISHED")
if textbox.text() == '':
textbox.setText(self.old_val['val'])
else:
self.old_val['val'] = textbox.text()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
widget = MainWidget()
widget.show()
sys.exit(app.exec_())