48

how can I make a QLabel to behave like a link? What I mean is that I'd like to be able to click on it and then this would invoke some command on it.

user336635
  • 2,081
  • 6
  • 24
  • 30

2 Answers2

117

QLabel does this already.

Sample code:

myLabel->setText("<a href=\"http://example.com/\">Click Here!</a>");
myLabel->setTextFormat(Qt::RichText);
myLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
myLabel->setOpenExternalLinks(true);
cmannett85
  • 21,725
  • 8
  • 76
  • 119
  • it for some bizarre reason doesn't want to behave like it should. How do you set the fnc/action it should invoke? – user336635 Dec 08 '11 at 10:00
  • 2
    You don't. When `openExternalLinks()` is true and the text interaction flags are set apprpriately, `QDesktopServices::openUrl()` is triggered carrying the URL of the label. – cmannett85 Dec 08 '11 at 10:24
  • thanks +1. Would you know if I can invoke via this regular fnc call – user336635 Dec 08 '11 at 14:27
  • If all Qlabel is doing is calling `QDesktopServices::openUrl()`, then you can just call that yourself. – cmannett85 Dec 08 '11 at 21:12
29

The answer from cmannnett85 is fine if you just want to open a URL when the link is clicked, and you are OK with embedding that URL in the text field of the label. If you want to do something slightly custom, do this:

QLabel * myLabel = new QLabel();
myLabel->setName("myLabel");
myLabel->setText("<a href=\"whatever\">text</a>");
myLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);

Then you can connect the linkActivated signal of the label to a slot, and do whatever you want in that slot. (This answer assumes you have basic familiarity with Qt's signals and slots.)

The slot might look something like this:

void MainWindow::on_myLabel_linkActivated(const QString & link)
{
    QDesktopServices::openUrl(QUrl("http://www.example.com/"));
}
David Grayson
  • 84,103
  • 24
  • 152
  • 189