简体   繁体   中英

Qtextbrowser pyqt5 problem after click on anchor

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_())

Before i clicked anchor: 在此处输入图像描述

After i clicked anchor: 在此处输入图像描述

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')

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM