QGraphicsTextItem
does not support this ability, as I'm sure you have discovered. So you have a few options:
- Reimplement
focusOutEvent(QFocusEvent* event)
and/orkeyReleaseEvent(QKeyEvent* event)
to detect when you validator needs to run. AQValidator
can be created as a member of your text class, and queried either when focus is lost and/or a key is pressed (the enter key to signify completion, or on every letter). Then just create a custom signal for you when deem the editing to have finished or changed. - Use a
GraphicsProxyWidget
to hold a 'real'QLineEdit
for text entry, just set it up with a validator as you would if placing in a traditional GUI form. You will need to 'forward' theeditingFinished()
ortextEdited(const QString& text)
signal from theQLineEdit
to yourQGraphicsTextItem
, so you don't have to provide external access to the widget. - You could also use the internal
QTextDocument
of theQGraphicsTextItem
, this is what actually holds and formats the text (access it withdocument()
). However it doesn't support having aQValidator
installed, so you would have to create a signal-slot loop whereby when the text is changed (signalled bycontentsChanged()
) it's received by theQGraphicsTextItem
, validated, then either updated/cleared if it fails validation (which will update theQTextDocument
, and trigger this process again) or ignored if it passes.
Neither is difficult to implement; the first requires more code but will give you more control over the visual appearance of the text box.