This is a small sample code for an application using socket. Аfter clicking on a link 'textlink' and adding untagged text by pressing 'add text' button, all subsequent text become hyperlink. By pressing gethtml button you can get html code in command line. Ho can i turn it off?
PS Adding a tag to every new line is not a solution.
import sys
from PyQt5.QtWidgets import *
class MainWindow(QMainWindow):
def __init__(self):
QMainWindow.__init__(self)
self.resize(500, 500)
self.browser = QTextBrowser(self)
self.browser.resize(500, 300)
self.btn = QPushButton('get html print', self)
self.btn.move(250, 400)
self.btn.clicked.connect(self.gethtml)
self.btn2 = QPushButton('add text', self)
self.btn2.move(150, 400)
self.btn2.clicked.connect(self.addtxt)
self.browser.setOpenLinks(False)
self.browser.anchorClicked.connect(self.anchor_clicked)
def gethtml(self):
print(self.browser.toHtml())
def addtxt(self):
self.browser.append('sample text 1')
self.browser.append('some text: <a href="http://link.com">textlink</a>')
self.browser.append('sample text 2')
def anchor_clicked(self):
pass
if __name__ == '__main__':
app = QApplication(sys.argv)
dlgMain = MainWindow()
dlgMain.show()
sys.exit(app.exec_())
CodePudding user response:
This is actually the expected behavior. As explained in the documentation of append()
:
Note: The new paragraph appended will have the same character format and block format as the current paragraph, determined by the position of the cursor.
This might be unintuitive for QTextBrowser, since it doesn't show the text cursor (the "caret"), but clicking on a QTextBrowser does change the cursor position, exactly like it would if you used setReadOnly(False)
or by using a standard QTextEdit.
The solution is to always move the text cursor to the end before calling append()
. Remember that in order to make the actual text edit/browser cursor move, you must call setTextCursor()
again after moving its position.
def addtxt(self):
# get the QTextCursor of the widget's document
cursor = self.browser.textCursor()
# move it to the end of the document
cursor.movePosition(cursor.End)
# *restore* the text cursor on the widget
self.browser.setTextCursor(cursor)
self.browser.append('sample text 1')
self.browser.append('some text: <a href="http://link.com">textlink</a>')
self.browser.append('sample text 2')