How to draw a rectangle around selected text in QPlainTextEditor in Qt?
Idea here is to let the user select as much text he wants in the text editor, then have a rectangle displayed around that selected area.
This rectangle has to take the shape of the selected text.
I found blockBoundingRect function which returns the bounding rectangle of the QTextBlock in the QTextBlock's own coordinates.
I am not sure if this would be of some help. What do I need to do to display the rectangle around the selected text?
Re: How to draw a rectangle around selected text in QPlainTextEditor in Qt?
I have discovered QRubberBand class. I don't know how to use it though, yet.
https://doc.qt.io/qt-5/qrubberband.html
Re: How to draw a rectangle around selected text in QPlainTextEditor in Qt?
Quote:
I don't know how to use it though, yet.
I don't think you want to use it for this purpose, though. A rubberband is generally used when selecting something - it has a starting anchor point that is established on a mouse press event, and then stretches as a line or a rectangle during mouse move events, and then is erased upon a mouse release.
In order to draw your rectangle on the text edit, you will probably have to derive a class from QPlainTextEdit and override the paintEvent(). Call the base class paintEvent() first, then use the QPainter to draw your rectangle.
You will have to evaluate the return value from the bounding rect for the QTextBlock to see if the coordinates make sense. If the coordinates seem to match up with the position of the text within the view, then just use them to draw your rect. If not, you may have to map them in some way to widget coordinates.
I am not familiar enough with QTextDocument to know how QTextBlock works. I don't know if a block has to align with paragraph boundaries of whether it can start and/or end within a paragraph. In addition, your user might select text that is only partly contained within a block, spans more than one block, or is in the interior of the block. In those cases, drawing a rectangle based on block coordinates would give a misleading representation of what the user had selected.
Re: How to draw a rectangle around selected text in QPlainTextEditor in Qt?
Thank you for the explanation.