Making QLabel behave like a hyperlink

前端 未结 2 978
名媛妹妹
名媛妹妹 2020-12-14 06:30

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.

相关标签:
2条回答
  • 2020-12-14 06:59

    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);
    
    0 讨论(0)
  • 2020-12-14 07:11

    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/"));
    }
    
    0 讨论(0)
提交回复
热议问题