I would like to launch URLs from a QTextEdit widget. The URLs are custom styled. I have made a naive attempt:

Writing text to the QTextEdit:
Qt Code:
  1. bool Text::WriteText( const QStringRef& str, bool inurl ) // Text is "public QTextEdit", inurl is true if we are appending an URL
  2. {
  3. if( !str.isEmpty() )
  4. {
  5. if( inurl )
  6. {
  7. QTextCharFormat cf(currentCharFormat());
  8.  
  9. cf.setAnchorHref(str.toString());
  10. mergeCurrentCharFormat(cf);
  11. }
  12.  
  13. insertPlainText(str.toString());
  14. }
  15.  
  16. return true;
  17. }
To copy to clipboard, switch view to plain text mode 

mouse click (debugging version for now, launch iceweasel when it will work):
Qt Code:
  1. void Text::mousePressEvent( QMouseEvent *event )
  2. {
  3. bool bb;
  4.  
  5. if( event->buttons() == Qt::LeftButton )
  6. {
  7. QTextCursor cu(cursorForPosition(event->pos()));
  8. QTextCharFormat cf(cu.charFormat());
  9. QString url(cf.anchorHref());
  10.  
  11. bb = url.isEmpty();
  12.  
  13. QTextEdit::mousePressEvent(event);
  14. }
  15. }
To copy to clipboard, switch view to plain text mode 

Works ... almost. If I click a URL in the text window, the "url" string contains the URL. If I click another URL, I get another URL correctly. But if I click a non-URL text, I get the last URL clicked. Not acceptable. What am I doing wrong?