I have a problem with text in QTextBrowser. I have a similar code:
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.textBox = QTextBrowser(centralWidget)
self.textBox.setOpenExternalLinks(True)
self.button = QPushButton(centralWidget)
self.button.setText("PUSH")
self.button.clicked.connect(self.pressed)
self.grid = QGridLayout(centralWidget)
self.grid.addWidget(self.button)
self.grid.addWidget(self.textBox)
def pressed(self):
id = 49309034
url_name = "test_link"
link = '<a href = https://stackoverflow.com/questions/{0}> {1} </a>'.format(id, url_name)
dict = {'Key': 'Value', link: 'Test link'}
for key, value in dict.items():
self.textBox.append('{0}: {1}'.format(key, value))
self.textBox.append("")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())
However, if I click on the link and then push button again - all text becomes 'hyperactive':
I think, the problem is in 'next line'. Because I've tried such code and it's working properly:
string = ""
for key, value in dict.items():
string += '{0}: {1}'.format(key, value) + '; '
self.textBox.append(string)
After I've clicked on the URL and pushed button
Can you help me figure this out?
Try moving the cursor before adding lines to QTextBrowser. For example, like this:
self.textBox.moveCursor(QTextCursor.Start)
from PyQt5.QtWidgets import *
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtCore import *
class MainWindow(QMainWindow):
def __init__(self, parent=None):
super(MainWindow, self).__init__(parent)
centralWidget = QWidget()
self.setCentralWidget(centralWidget)
self.textBox = QTextBrowser(centralWidget)
self.textBox.setOpenExternalLinks(True)
self.button = QPushButton(centralWidget)
self.button.setText("PUSH")
self.button.clicked.connect(self.pressed)
self.grid = QGridLayout(centralWidget)
self.grid.addWidget(self.button)
self.grid.addWidget(self.textBox)
def pressed(self):
self.textBox.moveCursor(QTextCursor.Start) # <---
id = 49309034
url_name = "test_link"
link = '<a href = https://stackoverflow.com/questions/{0}> {1} </a>'.format(id, url_name)
dict = {'Key': 'Value', link: 'Test link'}
for key, value in dict.items():
self.textBox.append('{0}: {1}'.format(key, value))
self.textBox.append("")
if __name__ == '__main__':
import sys
app = QApplication(sys.argv)
w = MainWindow()
w.show()
sys.exit(app.exec_())