I'm using a QTextBrowser
to display rich text including a number of images, each of them specified with a HTML <img>
tag and added as resources using QTextDocument::addResource()
.
What I'd like to be able to do is, in a context menu handler (i.e. with a mouse click position available), identify the image that the click was over. It's possible to tell whether the click is over an image, because cursorForPosition(event->pos()).block().text()
returns a string starting with Unicode 0xFFFC. Unfortunately the same string is returned for every image in the view.
It's possible to get all of the formats in use with QTextDocument::allFormats()
, identify which of those are image formats, and get their image resource name. Unfortunately there seems to be no way to get their actual display position or bounding rectangle.
From the documentation:
You can use
charFormat().toImageFormat().name()
on the cursor to extract the image's URL. Below is a self-contained example. There are two noteworthy details:The cursor will sometimes point one character prior to the image. Thus the workaround; it seems necessary for both Qt 4.8.5 and 5.1.1.
The pop-up menus should be shown asynchronously so as not to block the rest of the application. The example code provided in the documentation is a source of bad user experience and should be considered an evil abomination. All widgets can automatically delete themselves when they get closed, so the menus won't leak. A
QPointer
is used only to demonstrate this fact. It tracks the menu's lifetime and nulls itself when the menu deletes itself.