问题
I have a QTextBrowser where I've entered that sample text:
Column1 Column2
1 2 3 4 www.google.com
Between the columns there are tabs and between the numbers there are spaces. plainText=QTextBrowser.toPlainText() gives:
Column1 Column2
1 2 3 4 www.google.com
Now, i want to make the link clickable. By this, I'll set the text as html. I wrote some string operations with
WORDS = re.split("(\W+)",plainText)
That gives
['Column1', '\t', 'Column2', '\n', '1', ' ', '2', ' ', '3', ' ', '4', '\t', 'www', '.', 'google', '.', 'com', ' ', '']
and replaced "www" with the hyperlink in html-format
<a href=http://www.google.com>www.google.com</a>
Then, I deleted the items in WORDS: ".", "test", ".", "com".
['Column1', '\t', 'Column2', '\n', '1', ' ', '2', ' ', '3', ' ', '4', '\t', '<a href=http://www.google.com>www.google.com</a>', ' ', '']
Then I rebuild all the WORDS-parts again to a string, replacing the linebreak \n with
<br/>.
Now, when I set the string to the QTextBrowser, the link is displayed correctly and also clickable. Problem is: The entered text, as it is now html, ignores/removes all spaces (if more than one) and tabs! The output looks like (with the link now being blue and underlined)
Column1 Column2
1 2 3 4 www.google.com
How can I just make a hyperlink without the formatting being destroyed?
Perhaps I am on the wrong train??
回答1:
I think I got it. In case it might be useful, here is my solution: A html file does respect your format, if you put the style in the css to "pre", and not like QTextBrowser to "pre-wrap". Moreover, in the end the typed links can directly be replaced by the created hyperlinks.
The html file that is generated and setted to the QTextBrowser then partwise looks like:
<style type="text/css">#editor { white-space: pre; }</style>
<p id='editor', style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; -qt-block-indent:0; text-indent:0px;"><a name="editor"></a>Column1 Column2</p>
来源:https://stackoverflow.com/questions/17643238/qtextbrowser-hyperlinks-in-pyqt4