Bread_Editor/binary_text_edit.py

31 lines
1.1 KiB
Python
Raw Normal View History

#!/usr/bin/python3
from PyQt6.QtWidgets import QPlainTextEdit
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()
pos = cursor.position()
text = self.toPlainText()
text_length = len(text)
2024-11-20 16:20:04 +01:00
if not (pos + 1) % 9 == 0 or event.text() in {"", None}: # dont overwrite the separator character
super().keyPressEvent(event)
2024-11-20 16:20:04 +01:00
# skip over the separator character when the cursor is before it.
if (pos + 2) % 9 == 0 and not event.text() in {"", None}:
if pos == text_length: # append to the input if the cursor is at the end
self.insertPlainText(" ")
cursor = self.textCursor()
cursor.setPosition(pos + 2)
2024-11-20 16:20:04 +01:00
cursor.setPosition(pos + 2)
self.setTextCursor(cursor)
else:
event.ignore()