QLineEdit and pasted text
-
I have a line edit control with no validator set. When text is copied and pasted from an external source, I would like to be able to filter the text before, or possibly after, the text is inserted.
I cannot overload the public slot
QLineEdit::paste()
because it is not virtual. That would probably be the easiest and most straight-forward option.I can connect to the
textChanged()
signal, but I would need to know that the text was being pasted and not typed. Also, I would need to clear the current contents of the control before inserting the pasted text. Would thesender()
function help here?The actual use case is to try out a regular expression on a website such as
www.regex101.com
, copy the working pattern to the clipboard, and then paste it into my app. That site always prepends"/"
and appends"/gm"
to each pattern, so I would like to strip those off automatically if they are present. -
Another option would be to provide a button for inserting the text from the clipboard, where I have more control over the text. But how to know that some text was copied to the clipboard?
Is there some kind of
clipboard watcher
in Qt I could use? -
@Robert-Hairgrove said in QLineEdit and pasted text:
Is there some kind of clipboard watcher in Qt I could use?
You're welcome :)
In general,
QClipboard
might be a good idea to use in your caseEdit:
When text is copied and pasted from an external source, I would like to be able to filter the text before, or possibly after, the text is inserted.
Why not check every time the text changes?! Then you could make use of
textChanged()
signal...Another thing which comes to my mind, but not tested and no idea if this would work:
Catch the
keyPressEvent
and check for "Insert
" and "Ctrl + V
"QKey
/QKeyCombination
-
@Robert-Hairgrove said in QLineEdit and pasted text:
I cannot overload the public slot QLineEdit::paste() because it is not virtual.
But it is a slot:
class LineEdit : public QLineEdit { Q_OBJECT public slots: void paste() { qDebug()<<"paste"<<qApp->clipboard()->text(); insert(qApp->clipboard()->text()); } };
and you can insert/modify the text you want.
-
@Robert-Hairgrove said in QLineEdit and pasted text:
Where is the text coming from?
From the signal, or what is your question?
"I meant to say that I cannot override the slot" - you can always call the base class version in your override.
-
@Pl45m4 Thank you for the useful suggestions. I think I shall connect a slot to the
QClipboard::dataChanged()
signal in order to show a button which the user can press to paste the new text into the control.Of course, if the user pastes directly into the control with Ctrl-V, for example, or a context menu, then the text will not be filtered. Also not if typing, which is why I do not want to use
QValidator
. It is only for convenience, so using a separate button to insert the clipboard text gives me greater flexibility. -