gpt4 book ai didi

c++ - 如何在 QPlainTextEdit 中捕获链接点击事件

转载 作者:搜寻专家 更新时间:2023-10-31 00:31:41 24 4
gpt4 key购买 nike

如果我在 QPlainTextEdit 中使用 appendHtml 创建一个链接,我如何判断用户是否点击它,并对 URL 做些什么?没有点击 URL 的信号,就像在 QTextBrowser 中一样。

除了创建一个全新的 Qt 控件来执行此操作之外,还有什么方法可以实现此目的吗?

注意:我对 QTextEditQTextBrowser 等不同的组件不感兴趣,因为它们非常慢。我特别想在 QPlainTextEdit 或其任何定制中捕获链接点击,它们具有相同的性能。

最佳答案

函数QPlainTextEdit::anchorAt :

Returns the reference of the anchor at position pos, or an empty string if no anchor exists at that point.

要激活某个链接,用户应在该对象上按下鼠标左键,然后在该链接上松开鼠标左键。这可以通过 mousePressEventmouseReleaseEvent 进行跟踪。

不幸的是,没有简单的机制来检查释放按钮是否在同一个链接对象上释放。可以只比较 anchor 文本。因此,如果有多个 anchor 具有相同的链接,则可能会发生误报检测。如果这是一个问题,则可以通过检查文本选择状态来执行类似的技巧,如在 QTextBrowser 中,如果小部件文本是可选的。

最简单的实现:

#ifndef PLAINTEXTEDIT_H
#define PLAINTEXTEDIT_H

#include <QPlainTextEdit>
#include <QMouseEvent>

class PlainTextEdit : public QPlainTextEdit
{
Q_OBJECT

private:
QString clickedAnchor;

public:
explicit PlainTextEdit(QWidget *parent = 0) : QPlainTextEdit(parent)
{
}

void mousePressEvent(QMouseEvent *e)
{
clickedAnchor = (e->button() & Qt::LeftButton) ? anchorAt(e->pos()) :
QString();
QPlainTextEdit::mousePressEvent(e);
}

void mouseReleaseEvent(QMouseEvent *e)
{
if (e->button() & Qt::LeftButton && !clickedAnchor.isEmpty() &&
anchorAt(e->pos()) == clickedAnchor)
{
emit linkActivated(clickedAnchor);
}

QPlainTextEdit::mouseReleaseEvent(e);
}

signals:
void linkActivated(QString);
};

#endif // PLAINTEXTEDIT_H

信号 linkActivatedhref anchor 文本一起发出。例如,当激活以下 anchor 时,将使用字符串 "http://example.com" 发出信号:

QString html = "<a href='http://example.com'>Click me!</a>";
text->appendHtml(html);

关于c++ - 如何在 QPlainTextEdit 中捕获链接点击事件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33531632/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com