jeudi 31 août 2023

How to add an hyperlink to a QImage in a QTextTableCell?

My application has a pdf report creator which displays a table with some information. One of the columns must display a location pin icon and when clicked this must open a link to a google maps location.

I tried to use a HTML-formatted QString to create the link, something like this:

const QString html = "\<a style='font-size:8px;' href='http://www.google.com/maps/place/" + xPosStr + "," + yPosStr + "'\>" + "Location" + "</a>"

Then I insert this string by using the insertHtml method.

And as expected the table cell displays the link with the text "Location" on it. This text can be clicked and it opens my browser with the website correctly. But now I try to change the "Location" text to an image. This image is loaded using a QImage, not a QWidget, so I can't use any QWidget property because this process occurs outside of my UI thread. So when I change the HTML-formatted QString to something like this:

const QString html = "<a href='http://www.google.com/maps/place/" + xPosStr + "," + yPosStr + "'>" + "<img src='" + locationIcon + "'>" + "</a>";

This loads the image correctly but the href part is seemingly lost. Maybe it's because the QImage is not a clickable object. I'm not sure why this happens.

This method below will give more information about my problem:

void _setCellPositionImage(QTextTableCell cell, const Point& position, QTextChatFormat& charFormat)
{
    QTextBlockFormat centerAlignment;
    centerAlignment.setAlignment(Qt::AlignCenter);

    QTextCursor cellCursor = cell.firstCursorPosition();
    cellCursor.setBlockFormat(centerAlignment);
    cellCursor.mergeBlockCharFormat(imgFormat);

    const bool isValidPosition = !(is_near_zero(position.x) && is_near_zero(position.y));
    if (isValidPosition)
    {
        const QString xPosStr = QString::number(position.x, 'f', 6);
        const QString yPosStr = QString::number(position.y, 'f', 6);

        // This loads the image correctly but the href is lost.
        const QString html = "<a href='http://www.google.com/maps/place/" + xPosStr + "," + yPosStr + "'>" + "<img src='" + locationIcon + "'>" + "</a>";

        cellCursor.insertHtml(html);
    }
    else
    {
        cellCursor.insertText("--");
    }
}

I'm using C++11 and Qt 5.14. Thanks in advance.

Aucun commentaire:

Enregistrer un commentaire