【问题标题】:Editing behavior of “backspace” key of QDoubleSpinBoxQDoubleSpinBox 的“退格”键的编辑行为
【发布时间】:2017-04-06 23:39:16
【问题描述】:

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

我尝试调试“验证”方法中的内容,并得到了一个奇怪的结果: 当光标在“0,00m”末尾时按下“退格”,验证接收“0,00m”。 当光标位于“0,00_m”末尾时按下“退格”时,验证接收“0,00__m” 当光标位于“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_()

【问题讨论】:

    标签: python qt pyqt keyboard-events qspinbox


    【解决方案1】:

    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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2011-08-25
      • 1970-01-01
      • 2015-01-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多