Insert clickable link in QLabel and detect click on this link to provoke an action
Asked Answered
H

1

20

I would like to handle a click to the link in this application of mine:

my application

When I click on the "Output File" link, I would like to be able to generate an action in my application.

As of today, the link is described like this in the rich text QLabel:

<a href="http://google.fr"><span style=" text-decoration: underline; color:#0000ff;">Output File&quot;</span></a>

(generated by Qt Designer)

When clicked, it will open the default web browser to go to Google. That's not what I want; I'd like something like:

<a href="#browse_output"><span style=" text-decoration: underline; color:#0000ff;">Output File&quot;</span></a>

And be able to detect the link that's clicked and react accordingly:

(pseudo code)

if( link_clicked.toString() == "#browse_output" ){
    on_browse_output_clicked();
}

Is this possible in Qt with a QLabel (or something approaching) ? How?

Hawkbill answered 16/5, 2013 at 7:27 Comment(1)
You can try filtering events for QLabel, but I'm not sure how you will know where the link is.Paroxysm
H
40
  1. Disable the "openExternalLinks" property of the QLabel
  2. Connect the signal linkActivated of the QLabel to your handler.

That's all: linkActivated gives you the URL that the link refers to in the argument, so my pseudocode works perfectly.

// header
private slots:
  void on_description_linkActivated(const QString &link);

// cpp
void KernelBuild::on_description_linkActivated(const QString &link)
{
  if( link == "#browse_output" ){
    on_outfilebtn_clicked();
  }
}
Hawkbill answered 16/5, 2013 at 7:37 Comment(3)
Strange thing, basic links like http:// or mailto: are not opening browser/mail application. Using this code + QDesktopServices::openUrl I could make it work.Aeri
@Borzh: you just need to set the text interaction flags beforehand. For instance: item->setTextInteractionFlags(Qt::TextBrowserInteraction); item->setOpenExternalLinks(true); item->setHtml(/*whatever*/);. In this working example item is a QGraphicsTextItem*. No need for QDesktopServices::openUrl or custom signals / handlers.Hulen
What would cause linkActivated to not fire. I am doing exactly this but linkActivated never fires.Hymie

© 2022 - 2024 — McMap. All rights reserved.