Set anchor for textCursor for matching regex

203 views Asked by At

With a regex i found out all the links in the text. Now how can I select only the links for themselves and insert an anchor?

I have already used:

cur=self.textedit.textCursor()
cur.select(QTextCursor.Document)
fmt=QTextCharFormat()
fmt.setAnchorHref(link)
cur.mergeCharFormat(fmt)

This has the problem that the whole text is made as a link. Thats because i select the whole document, I know. But then how can I automatically select the found links? For example if the text is

Hello world this is a link to www.google.com and it does not work so I ask at www.stackoverflow.com.

I would like the www.google.com and www.stackoverflow.com to be selected automatically. Those exact two strings I already have found by a regex.

EDIT:

I found a way to select the links. At first I get the index of a link by

link="www.google.com"
text=self.textedit.toPlainText()
selectTextAt = text.index(link)

cur=self.textedit.textCursor()
cur.setPosition(selectTextAt)
cur.movePosition(QTextCursor.Right, QTextCursor.KeepAnchor, len(link))
self.textedit.setTextCursor(cur)

Or even better:

cur=self.textedit.document().find(link,cur)
self.textedit.setTextCursor(cur)

createHyperlink=cur.selectedText()
fmt=QTextCharFormat()
fmt.setAnchorHref(createHyperlink)
cur.mergeCharFormat(fmt)

Then I have two other problems:

  • the link is only shown after i re-set the text as html

  • If I click the link, nothing happens but every text gets cleared.

Typing the html into phase5 (html-editor) it seems like the links only work if they are like "a href="http://..:" and not "a href="www....". Do you have any suggestions?

0

There are 0 answers