按模式制作所有匹配链接

问题描述

我需要在 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.JdbcOdbc...