微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

按模式制作所有匹配链接

如何解决按模式制作所有匹配链接

我需要在 QPlainTextEdit 中按模式创建所有匹配链接,例如:

https://stackoverflow.com/questions/ask b;aaskdfjakjf oasfdjoiasjdas oiajsdj blalvballvlalvllkasln https://google.com/

https://stackoverflow.com/questions/askhttps://google.com/ - 应该变成链接,您可以关注它们。

我使用 hightlighter 类进行搜索匹配和更改文本块。

代码: SearchHighLight.h

#ifndef SEARCHHIGHLIGHT_H
#define SEARCHHIGHLIGHT_H

#include <QSyntaxHighlighter>
#include <QRegularExpression>

class SearchHighLight : public QSyntaxHighlighter
{
    Q_OBJECT
    using BaseClass = QSyntaxHighlighter;
public:
    explicit SearchHighLight(QTextDocument* parent = nullptr);
    void searchText(const QString& text,QRegularExpression::Patternoption option);
protected:
    virtual void highlightBlock(const QString &reqularExpressoin) override;
private:
    QRegularExpression m_pattern;
    QTextCharFormat m_format;
};

#endif // SEARCHHIGHLIGHT_H

SearchHighLight.cpp

#include "searchhighlight.h"

SearchHighLight::SearchHighLight(QTextDocument* parent) : BaseClass(parent)
{
    //m_format.setBackground(Qt::green);
}

void SearchHighLight::highlightBlock(const QString& reqularExpressoin)
{
    QRegularExpressionMatchIterator matchIterator = m_pattern.globalMatch(reqularExpressoin);

    m_format.setAnchor(true);
    m_format.setAnchorHref("https://www.google.com/");
    
    while (matchIterator.hasNext())
    {
        QRegularExpressionMatch match = matchIterator.next();
        setFormat(match.capturedStart(),match.capturedLength(),m_format);
    }
}

void SearchHighLight::searchText(const QString& text,QRegularExpression::Patternoption option)
{
    m_pattern = QRegularExpression(text,option);
    rehighlight();
}

试试:

MainWindow::MainWindow(QWidget *parent)
    : QMainWindow(parent)
{
    this->setFixedSize(800,600);

    mainW = new QWidget(this);
    mainW->setGeometry(0,800,600);
    lay = new qgridLayout(mainW);

    te = new QPlainTextEdit(mainW);
    lay->addWidget(te,1,6);

    m_searchHighLight = new SearchHighLight(te->document());

    te->setPlainText("https://www.google.com/");

    m_searchHighLight->searchText("(https)(.+)(\\S)",QRegularExpression::nopatternoption);
}

什么都没发生。 备注:

  1. 正则表达式是正确的
  2. 无法使用 html
  3. Highlighter 可以正常使用:m_format.setBackground(Qt::green);

如何正确使用 QTextCharFormat 使其发挥作用?

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其他元素将获得点击?
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。)
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbcDriver发生异常。为什么?
这是用Java进行XML解析的最佳库。
Java的PriorityQueue的内置迭代器不会以任何特定顺序遍历数据结构。为什么?
如何在Java中聆听按键时移动图像。
Java“Program to an interface”。这是什么意思?