QDoubleSpinBox“backspace”键的编辑行为

2024-09-22 20:30:29 发布

您现在位置:Python中文网/ 问答频道 /正文

我对QDoubleSpinBox有问题。在某种程度上,键的行为取决于键后缀的大小。 如果我将“m”设置为后缀,然后将光标设置在数字调整框的末尾并按“backspace”,则光标将跳过“m”后缀,然后可以使用进一步的“backspaces”编辑该值。 如果我将后缀设置为“mm”或任何双字母单词,则无论我按多少个“backspaces”,光标都将保留在微调框的末尾。在

我试着调试“validate”方法,得到了一个奇怪的结果: 当光标在“0,00m”的末尾按下“backspace”时,validate接收到“0,00m”。 当光标在“0,00”末尾按下“退格”键时,validate接收到“0,00μm” 当光标在“0,00 mm”的末尾按下“backspace”时,validate接收到“0,00 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_()

Tags: textselfdefresvalidate后缀sbmm
1条回答
网友
1楼 · 发布于 2024-09-22 20:30:29

当涉及到关键事件处理时,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)

相关问题 更多 >