Qt Editable QGraphicsTextItem checking text and signaling when changing

I am really obsessed with the task related to Qt GraphicsView. Any help or suggestions would be greatly appreciated. In my QGraphicsView application, I have some editable QGraphicsTextItems that I added to the scene. I need the following functionality:

  • Setting a validator for float so that the user does not mistakenly enter a character or a new line in this text element.
  • Emission of a signal after a user changes text.

Can anyone suggest how I can implement this in my application? I tried hard, but I can not find anything suitable. If there is any alternative or workaround, I will be grateful for that.

Thanks!

+4
source share
1 answer

QGraphicsTextItem does not support this ability, as I am sure you discovered. Thus, you have several options:

  • Reimplement focusOutEvent(QFocusEvent* event) and / or keyReleaseEvent(QKeyEvent* event) to determine when to keyReleaseEvent(QKeyEvent* event) validator. A QValidator can be created as a member of your text class and requested either when you lose focus or when you press a key (the enter key means completion or for each letter). Then just create a custom waveform for you if you think the editing is complete or changed.
  • Use GraphicsProxyWidget to store the β€œreal” QLineEdit for text input, just set it using the validator, as if you placed it in the traditional form of the graphical interface. You will need to β€œforward” the editingFinished() or textEdited(const QString& text) signal from QLineEdit to QGraphicsTextItem , so you do not need to provide external access to the widget.
  • You can also use the internal QTextDocument QGraphicsTextItem , this is what actually executes and formats the text (accessed via document() ). However, it does not support the installation of QValidator , so you will need to create a signal slot loop, as a result of which when changing the text (with contentsChanged() message) it will be received by QGraphicsTextItem , checked, or updated / cleared if it does not pass the check (which will update QTextDocument and starts this process again) or will be ignored if it passes.

It is also difficult to implement; the first requires more code, but will give you more control over the visual appearance of the text field.

+6
source

Source: https://habr.com/ru/post/1485923/


All Articles