From 93408e9a29ace47c80f88ad56e4ce86d194da78e Mon Sep 17 00:00:00 2001 From: EKNr1 Date: Mon, 9 Dec 2024 17:26:28 +0100 Subject: [PATCH] Implemented deleting of bytes. --- binary_text_edit.py | 32 +++++++++++++++++++++++++++----- 1 file changed, 27 insertions(+), 5 deletions(-) diff --git a/binary_text_edit.py b/binary_text_edit.py index 337b0bb..90ef344 100644 --- a/binary_text_edit.py +++ b/binary_text_edit.py @@ -1,6 +1,7 @@ #!/usr/bin/python3 from PyQt6.QtWidgets import QPlainTextEdit +from PyQt6.QtCore import Qt class BinaryTextEdit(QPlainTextEdit): # rewrite QPlainTextEdit.keyPressEvent because it has no .setValidator() @@ -9,19 +10,40 @@ class BinaryTextEdit(QPlainTextEdit): # rewrite QPlainTextEdit.keyPressEvent be if event.text() in allowed_keys: cursor = self.textCursor() - pos = cursor.position() + position = cursor.position() text = self.toPlainText() text_length = len(text) - if not (pos + 1) % 9 == 0 or event.text() in {"", None}: # dont overwrite the separator character + if not (position + 1) % 9 == 0 or event.text() in {"", None}: # dont overwrite the separator character super().keyPressEvent(event) # skip over the separator character when the cursor is right before it. - if (pos + 2) % 9 == 0 and not event.text() in {"", None}: - if pos == text_length - 1: # append to the input if the cursor is at the end + if (position + 2) % 9 == 0 and not event.text() in {"", None}: + if position == text_length - 1: # append to the input if the cursor is at the end self.insertPlainText(" 00000000") - cursor.setPosition(pos + 2) + cursor.setPosition(position + 2) + self.setTextCursor(cursor) + + elif event.key() == Qt.Key.Key_Backspace or event.key() == Qt.Key.Key_Delete: + # delete last byte when backspace or delete is pressed + text = self.toPlainText() + + if len(text) >= 9: + cursor = self.textCursor() + position = cursor.position() + + text = text[:-9] # delete last byte + + self.setPlainText(text) + + # calculate the new cursor position (by subtracting 9, we set the position to the same bit but one byte + # before and by floor dividing this by 9 we get the "byte index" and when we multiply this by 9, we get + # the character position of the first bit in that byte.) + position = (position - 9) // 9 * 9 + + cursor.setPosition(position) + self.setTextCursor(cursor) else: