我需要按模式创建所有匹配链接QPlainTextEdit
,例如:
https://stackoverflow.com/questions/ask b;aaskdfjakjf oasfdjoiasjdas oiajsdj blalvballvlalvllkasln https://google.com/
https://stackoverflow.com/questions/ask和https://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,0, 800, 600);
lay = new QGridLayout(mainW);
te = new QPlainTextEdit(mainW);
lay->addWidget(te, 1, 1, 1, 6);
m_searchHighLight = new SearchHighLight(te->document());
te->setPlainText("https://www.google.com/");
m_searchHighLight->searchText("(https)(.+)(\\S)", QRegularExpression::NoPatternOption);
}
什么都没发生。评论:
- 正则表达式是正确的
- 无法使用 html
Highlighter
如果使用可以正常工作:m_format.setBackground(Qt::green);
如何QTextCharFormat
正确使用使其工作?