如果您在“年龄”字段中输入小于 18 且大于 80 的数字,然后单击QPushButton
(按钮将保持灰色)或打开QRadioButton
(圆圈将变为蓝色),程序会出现视觉错误。
有什么办法可以去掉这个吗?当您单击另一个字段LineEdit
时,没有类似的东西。
from PySide6 import QtWidgets, QtCore, QtGui
class QTApp(QtWidgets.QWidget):
def __init__(self):
super(QTApp, self).__init__()
self.LE_sample_input_01 = QtWidgets.QLineEdit()
self.LE_sample_input_02 = QtWidgets.QLineEdit()
self.LE_sample_input_01.setPlaceholderText('Возраст')
self.RadioButton = QtWidgets.QRadioButton('Что-то')
self.Button = QtWidgets.QPushButton('Тык')
self.Button.setStyleSheet("QPushButton:pressed {background-color: #b3b3ba;}")
layout = QtWidgets.QVBoxLayout(self)
layout.addWidget(self.LE_sample_input_01)
layout.addWidget(self.LE_sample_input_02)
layout.addWidget(self.RadioButton)
layout.addWidget(self.Button)
self.LE_sample_input_01.installEventFilter(self)
def eventFilter(self, obj, event):
if event.type() == QtCore.QEvent.FocusOut and QtGui.QFocusEvent.reason(event) == QtCore.Qt.MouseFocusReason:
if obj is self.LE_sample_input_01:
try:
age = int(self.LE_sample_input_01.text())
if age < 18 or age > 80:
error = QtWidgets.QMessageBox()
error.setWindowTitle('Ошибка возраста')
error.setText('Возраст введён неверно (от 18 до 80 лет)')
error.setIcon(QtWidgets.QMessageBox.Warning)
error.addButton('Ок',QtWidgets.QMessageBox.AcceptRole)
error.exec()
obj.setFocus()
obj.selectAll()
return True
except: pass
return False
if __name__ == "__main__":
app = QtWidgets.QApplication()
qt_app = QTApp()
qt_app.show()
app.exec()
试试这样:
SP_MessageBoxCritical.png