C++ 使 QLabel 表现得像一个超链接

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/8427446/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-28 18:33:32  来源:igfitidea点击:

Making QLabel behave like a hyperlink

c++qt

提问by user336635

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.

我怎样才能让 QLabel 表现得像一个链接?我的意思是我希望能够点击它,然后这会调用它的一些命令。

回答by cmannett85

QLabel does this already.

QLabel已经这样做了

Sample code:

示例代码:

myLabel->setText("<a href=\"http://example.com/\">Click Here!</a>");
myLabel->setTextFormat(Qt::RichText);
myLabel->setTextInteractionFlags(Qt::TextBrowserInteraction);
myLabel->setOpenExternalLinks(true);

回答by David Grayson

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:

如果您只想在单击链接时打开一个 URL,并且您可以将该 URL 嵌入到标签的文本字段中,那么来自 cmannnett85 的答案很好。如果您想做一些稍微自定义的事情,请执行以下操作:

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

Then you can connect the linkActivatedsignal 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.)

然后你可以将linkActivated标签的信号连接到一个插槽,并在该插槽中做任何你想做的事情。(这个答案假设您基本熟悉 Qt 的信号和槽。)

The slot might look something like this:

该插槽可能如下所示:

void MainWindow::on_myLabel_linkActivated(const QString & link)
{
    QDesktopServices::openUrl(QUrl("http://www.example.com/"));
}