[英]Qtextbrowser pyqt5 problem after click on anchor
这是一个使用套接字的应用程序的小示例代码。 在单击链接“textlink”并通过按“添加文本”按钮添加未标记文本后,所有后续文本都将变为超链接。 通过按 gethtml 按钮,您可以在命令行中获取 html 代码。 我可以关掉它吗?
PS 为每个新行添加标签不是解决方案。
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_())
这实际上是预期的行为。 如append()
的文档中所述:
注意:附加的新段落将具有与当前段落相同的字符格式和块格式,由 cursor 的 position 确定。
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。
解决方案是在调用append()
之前始终将文本 cursor 移动到末尾。 请记住,为了使实际的文本编辑/浏览器 cursor 移动,您必须在移动其 position 后再次调用setTextCursor()
。
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')
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.