c++qt5tooltipqlabel

Set a tooltip for a hypertext link in a QLabel


I have a QLabel with an embedded link:

QString LinkName ("...") ;
QString DestName ("...") ;
QLabel* myLabel ;
...
myLabel -> setText (QString ("Click <a href=\"%1\">here</a> to go to %2")
  .arg (LinkName).arg (DestName))) ;

The label is displayed centred in its owner widget.

I want to set a tooltip on the LinkName text, i.e. the clickable text that appears underlined in the QLabel. But I don't know where it is, because I don't know DestName in advance. Is there a way to do this? (I am using Qt5.)

The comments show how to dynamically set a tootip. But how do I know where its rectangle should be? How can I find out the coordinates of the "here" text?

I tried

"Click <a href=\"%1\" title=\"Tooltip text\">here</a> to go to %2"

but it has no effect.

Edited to add: This Qt Forum entry seems to suggest that what I want is not supported: "The Qt rich text does not include tooltips, unfortunately."


Solution

  • It's possible to replicate HTML title Attribute in Qt using a combination of QLabel::linkHovered and QToolTip::showText which is static.

    #include <QApplication>
    #include <QtWidgets>
    
    int main(int argc,char*argv[])
    {
        QApplication a(argc, argv);
    
        QString LinkName("linkName");
        QString DestName("destName");
        QLabel myLabel;
    
        myLabel.setText(QString("Click <a href=\"%1\">here</a> to go to %2").arg (LinkName).arg(DestName)) ;
    
        QObject::connect(&myLabel,&QLabel::linkHovered,[=](const QString &link)
        {
            //link is passed from linkHovered signal as a QString
            //use current cursor position to display the tooltip there
            QToolTip::showText(QCursor::pos(), link);
        });
    
        myLabel.show();
    
        return a.exec();
    }
    

    Link tooltip in a QLabel