我对QDoubleSpinBox有意见。“backspace”键的编辑行为在某种程度上取决于后缀的大小。如果我将“m”设置为后缀,然后将光标设置在“spinbox”的末尾,然后按下“backspace”,光标就会跳过“m”后缀的值,然后再用“backspace”进行编辑。如果我将后缀设置为“mm”或任何双字母单词,则无论按多少个“backspaces”,光标都保留在旋量框的末尾。
我试着调试“验证”方法中的内容,并得到了一个特殊的结果:当游标位于"0,00m“的末尾时,按下”backspace“,validate接收"0,00m”。当光标位于"0,00_m“的末尾时,当”backspace“被按下时,当”backspace“被按下时,当游标位于"0,00_mm”的末尾时,验证会收到"0,00_m_mm“。
造成这种行为的原因是什么,我如何克服它?
# coding=utf-8
from PyQt5 import QtWidgets
class SpinBox(QtWidgets.QDoubleSpinBox):
def __init__(self):
super().__init__()
def validate(self, text, index):
res = super().validate(text, index)
print(text, res, self.text())
return res
if __name__ == "__main__":
q_app = QtWidgets.QApplication([])
sb = SpinBox()
sb.setSuffix(" m")
sb.show()
q_app.exec_()发布于 2016-11-23 20:00:27
当涉及到关键事件处理时,QDoubleSpinBox/QAbstractSpinBox的源代码非常复杂--我无法确定默认行为应该是什么,甚至可能在哪里实现。在某个地方可能有个窃听器,但我不想赌它。
看起来唯一的选择就是重新实现keyPressEvent
class SpinBox(QtWidgets.QDoubleSpinBox):
def keyPressEvent(self, event):
if event.key() == QtCore.Qt.Key_Backspace:
suffix = self.suffix()
if suffix:
edit = self.lineEdit()
text = edit.text()
if (text.endswith(suffix) and
text != self.specialValueText()):
pos = edit.cursorPosition()
end = len(text) - len(suffix)
if pos > end:
edit.setCursorPosition(end)
return
super().keyPressEvent(event)https://stackoverflow.com/questions/40756382
复制相似问题