0

ALL,

In here I got a suggestion to override keyPressEvent in order to give a notification about the maximum length limit for QLineEdit.

However, I believe this won't work if I try to paste the text from keyboard either by using Ctrl+V or context menu.

What is the best way to do it in this case?

One more time: I'm looking for a way to notify the user about maximum length limit.

TIA!!

Igor
  • 5,620
  • 11
  • 51
  • 103
  • Override more events, to catch all the ways of paste happening? If you have trouble finding the right events (keyboard paste, context menu paste, drag&drop at least), you could use event filter with debug prints to see what events, exactly, the widget is getting. – hyde Dec 11 '18 at 20:57
  • You could also set max length property to be longer than the actual max you want, and then catch textChanged signal. Then you can notify user and truncate text if it is too long. – hyde Dec 11 '18 at 20:59
  • @hyde. presumably I need QLineEdit::paste() slot, but I have no idea how to do it. Or maybe there will be something different? – Igor Dec 11 '18 at 22:31
  • @hyde, I tgried Naidu's idea. I even tried to override the textEdited virtual function. Nothing. Anything else? – Igor Dec 12 '18 at 16:07

1 Answers1

1

Before 5.12:

Handle the textChanged signal of QLineEdit.

connect(lineEdit, SIGNAL(textChanged(const QString &)), this, SLOT(lineEditTextCahnged(const QString&)));

Now in the slot, look for clip board text. If both are same, then it is a kind of paste action. Then validate your length. Soem psudo-code below.

void yourclass::lineEditTextCahnged(const QString& text)
{

        QClipboard *pBoard = QApplication::clipboard();
        QString clipStr = pBoard->text();

        if (clipStr == text)
        {

           //THEN IT IS SOME PASTE ACTION.
           //HANDLE YOUR LENGTH VALIDATION.

        }
}

Version 5.12:

Handle void QLineEdit::inputRejected() signal

The documentation says

Note: This signal will still be emitted in a case where part of the text is accepted but not all of it is. For example, if there is a maximum length set and the clipboard text is longer than the maximum length when it is pasted.

http://doc.qt.io/qt-5/qlineedit.html#inputRejected

Pavan Chandaka
  • 11,671
  • 5
  • 26
  • 34
  • 1
    this signal is new since 5.12. If you look at the OP from the link I referenced, I asked for the version 5.11 or below. – Igor Dec 11 '18 at 22:25
  • @Igor could you please try the updated anwer?. Check if it works. Got this idea from googling of paste handling. – Pavan Chandaka Dec 11 '18 at 22:57
  • I will try that. But I know that the signal doesn't fire for the simple keyboard input. Maybe it will work for clipboard paste? I will let you know. It will be later today or tomorrow. – Igor Dec 11 '18 at 23:01