#!/usr/bin/python3 from PyQt6.QtWidgets import QPlainTextEdit from PyQt6.QtCore import Qt class BinaryTextEdit(QPlainTextEdit): # rewrite QPlainTextEdit.keyPressEvent because it has no .setValidator() def keyPressEvent(self, event): allowed_keys = {"", "0", "1"} if event.text() in allowed_keys: cursor = self.textCursor() position = cursor.position() text = self.toPlainText() text_length = len(text) 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 (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(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: event.ignore()