Hi there,

I want to make a QPlainTextEdit component restricting the input to only the characters '0' and '1'. Besides that, all the "control keys" for cut/copy/paste, tab for focus change etc. shall still work. So far, I haven't been successful and thus, asking for your help.

My expectation was, that QPlainTextEdit has one method where all the text going inside is handled. As far as I can tell, that is not the case.

Here is what I have done so far:

----
Idea #1: Use some signal/slot to intercept text which shall not go inside the edit. The obvious is the textChanged() signal but this is called if the text is already placed in the editor (too late).
Is there a signal which is called before the text is placed in the edit?

-----
Idea #2: Install event filter and discard all input except '0' and '1'
Qt Code:
  1. MyQPlainTextEdit edit;
  2. ..
  3. MyQPlainTextEdit::MyQPlainTextEdit(QWidget *parent) : QPlainTextEdit(parent) {
  4. ...
  5. installEventFilter(this);
  6. }
  7.  
  8. bool MyQPlainTextEdit::eventFilter(QObject* obj, QEvent* event) {
  9. if (event->type() == QEvent::KeyPress) {
  10. QKeyEvent* keyEvent = static_cast<QKeyEvent*>(event);
  11.  
  12. if ((keyEvent->text() != "") && (keyEvent->text() != "0") && (keyEvent->text() != "1")) {
  13. return true;
  14. }
  15. }
  16.  
  17. // standard event processing
  18. return QObject::eventFilter(obj, event);
  19. }
To copy to clipboard, switch view to plain text mode 

The problem is that I cannot reliable distinguish between actual characters shown in the widget and keystrokes potentially doing some control things. For example: I can enter a '0' or '1' (shows up in the text) or I can enter a Ctrl-'0' or Ctrl-'1' (works also with AltGr and so on).
I feel that intercepting plain key event is a bit too low level for my purpose...
---

Idea #3
Using a custom QTextCursor and overriding insertText(). As it turns out, these methods are only called if I insert text into the editor programmatically. User input is not seen by these functions.

-----

What am I doing wrong? What do you suggest? Thanks for your help and any hits you can give me!

Regards,
Paul