我有一个文本编辑器,可以将拉丁键盘按键转换为俄语字符。我重新实现了一个 QTextEdit 类:
class MyTextEdit(QTextEdit):
def __init__(self, *args):
QTextEdit.__init__(self, *args)
leftMousePressedSignal = pyqtSignal(QPoint)
rightMousePressedSignal = pyqtSignal(QPoint, QEvent)
mouseMovedSignal = pyqtSignal(QPoint)
mouseDoubleClickedSignal = pyqtSignal(QPoint)
keyPressedSignal = pyqtSignal(QEvent)
def mousePressEvent(self, event):
pos = event.pos()
if event.button() == Qt.LeftButton:
self.leftMousePressedSignal.emit(pos)
elif event.button() == Qt.RightButton:
self.rightMousePressedSignal.emit(pos, event)
def mouseMoveEvent(self, event):
if event.buttons() & Qt.LeftButton:
pos = event.pos()
self.mouseMovedSignal.emit(pos)
def mouseDoubleClickEvent(self, event):
if event.button() == Qt.LeftButton:
pos = event.pos()
self.mouseDoubleClickedSignal.emit(pos)
def keyPressEvent(self, event):
if event.type() == QEvent.KeyPress:
self.keyPressedSignal.emit(event)
然后我将其与重新实现的 keyPressEvent 一起使用。所以我还必须重新实现 Backspace 操作:
self.textEdit = MyTextEdit(self)
...
self.textEdit.keyPressedSignal.connect(self.OnKeyPressed)
self.actionSelectAll.triggered.connect(self.textEdit.selectAll)
...
def OnKeyPressed(self, event):
key = event.key()
txt = str(event.text())
if key == Qt.Key_Backspace:
if self.cursor.hasSelection():
self.cursor.movePosition(QTextCursor.NoMove, QTextCursor.KeepAnchor, self.cursor.selectionStart() - self.cursor.selectionStart())
else:
self.cursor.movePosition(QTextCursor.PreviousCharacter, QTextCursor.KeepAnchor, 1)
self.textEdit.setTextCursor(self.cursor)
self.textEdit.cut()
elif key == Qt.Key_A and (event.modifiers() & Qt.ControlModifier):
self.textEdit.selectAll()
现在,如果没有选择任何内容并且我按 Backspace,它会删除光标左侧的单个字符。当用鼠标选择一个单词并按 Backspace 时,它会删除该单词。当用鼠标选择几个单词或整个文本并按 Backspace 时,它会删除整个选择。所以,它工作正常。当我按下全选按钮(或 Ctrl+A)时 - 它会选择整个文本。但是,如果我然后按 Backspace,它只会删除光标左侧的 1 个字符,而不是整个文本。
如果您冷冷地告诉我我在这里做错了什么,我将不胜感激。谢谢你。