Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

[solved] Going through the links (<a> tags) in a QTextEdit



  • I have a QTextEdit in which the user can insert text and links (<a>, anchors). I need a way to loop through the links entered by the user and also to know their context (the text before and after every link). I tried going through all the QTextBlocks in the corresponding QTextDocument and use the QTextBlock::text() method but what I see are the lines in the QTextEdit and the links are converted to plain text. What I want to do with the links is to make a function similar with QTextEdit::toPlainText but which prints links in the text in a different way, such as {{http://www.google.com/}} (between two {{ and }} for example).


  • Moderators

    An ugly regexp might do the job:
    @
    auto text = textEdit->toHtml();
    QRegExp exp("<\sa\s+[^>]href\s=\s\"([^\"])\"\s>(.)<\/\sa\s*>");
    text.replace(exp, "{{\1}}");
    textEdit->setHtml(text);
    @



  • Thank you. Your code worked well. I also used this statement
    @exp.setMinimal(true);@

    before this one:
    @text.replace(exp, "{{\1}}");@



  • Thanks for posting your solution here for the benefit of others.

    Please add [solved] to the topic so everyone can see that this problem is solved. You can do that by editing your first post.


Log in to reply