我正在使用 PyQt5 开发费用管理应用程序,我需要在金额字段中允许空格,同时限制其他非数字输入。我的目标是使用户能够输入多个金额,并用空格分隔。我已经实现了一个事件过滤器来限制输入,但我在允许空格以及数字和小数点时遇到问题。
这是我的代码的相关部分:
class ExpenseManager(QtWidgets.QMainWindow):
def __init__(self):
super().__init__()
self.setup_ui()
self.install_event_filters()
def setup_ui(self):
# Setup UI components (simplified for brevity)
self.amount = QtWidgets.QLineEdit(self)
self.itemName = QtWidgets.QLineEdit(self)
self.date = QtWidgets.QDateEdit(self)
self.note = QtWidgets.QTextEdit(self)
self.accountDropdown = QtWidgets.QComboBox(self)
self.statusBar = QtWidgets.QStatusBar(self)
self.setStatusBar(self.statusBar)
# Additional UI setup...
def add_expense(self):
amount_text = self.amount.text()
item = self.itemName.text().upper()
date = self.date.date().toString('yyyy-MM-dd')
time = datetime.now().strftime("%H:%M:%S")
note = self.note.toPlainText().upper()
account = self.accountDropdown.currentText()
if amount_text and item and account:
amounts = amount_text.split()
try:
# Check if all amounts are valid numbers
amounts = [float(amount) for amount in amounts]
self.c.execute("SELECT id, name FROM accounts WHERE name = ?", (account,))
account_row = self.c.fetchone()
if account_row:
account_id = account_row[0]
account_on = account_row[1]
for amount in amounts:
self.c.execute("INSERT INTO expenses (amount, item, date, time, note, account_on, account_id) VALUES (?, ?, ?, ?, ?, ?, ?)",
(amount, item, date, time, note, account_on, account_id))
self.conn.commit()
if self.completer_note:
self.completer_note.model().setStringList(self.get_notes())
self.amount.clear()
self.itemName.clear()
self.date.setDate(QtCore.QDate.currentDate())
self.note.clear()
self.statusBar.showMessage("Expense(s) added successfully", 3000)
self.amount.setFocus()
else:
self.statusBar.showMessage("Selected account does not exist", 3000)
except ValueError:
self.statusBar.showMessage("Please enter valid amount(s)", 3000)
else:
self.statusBar.showMessage("Please fill all mandatory(*) fields", 3000)
self.completer.model().setStringList(self.get_items())
self.completer_note.model().setStringList(self.get_notes())
def install_event_filters(self):
self.amount.installEventFilter(self)
self.itemName.installEventFilter(self)
self.note.installEventFilter(self)
self.date.lineEdit().installEventFilter(self)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.KeyPress:
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
if obj == self.date.lineEdit():
self.add_expense()
return True
elif obj == self.note:
if event.modifiers() & QtCore.Qt.ControlModifier:
return False
else:
self.add_expense()
return True
elif obj == self.itemName:
if event.key() == QtCore.Qt.Key_Return or event.key() == QtCore.Qt.Key_Enter:
if self.itemName.completer().popup().isVisible():
return False
else:
self.add_expense()
return True
if isinstance(obj, QtWidgets.QLineEdit) or isinstance(obj, QtWidgets.QTextEdit):
if event.text().isalpha():
obj.insert(event.text().upper())
return True
return super().eventFilter(obj, event)
在 eventFilter 中,我尝试在下面添加此行,但没有成功:
if event.text() == ' ' or event.text().isalnum():
obj.insert(event.text())
return True
使用此代码,我尝试在金额字段中允许数字、空格和小数点。但是,该代码没有按预期工作。金额字段仍然不接受空格。
我应该进行哪些更改才能确保金额字段允许空格,同时限制其他非数字输入?
如有任何帮助,我们将不胜感激。谢谢!
此类任务的通常解决方案是QValidator。例如,以下正则表达式允许带有可选前导和尾随空格的正整数:
amount.setValidator(QRegularExpressionValidator(QRegularExpression("(\s?)+[0-9]+(\s?)+")))
其他字段也可能具有以下日期和时间模板:
date.setValidator(QRegularExpressionValidator(QRegularExpression("[0-9]{0,4}-[0-9]{0,2}-[0-9]{0,2}")))
time.setValidator(QRegularExpressionValidator(QRegularExpression("[0-9]{0,2}:[0-9]{0,2}:[0-9]{0,2}")))