1

I'm having trouble getting QTextBrowser.scrollToAnchor to scroll properly. The on_anchorClicked signal is firing, but I'm having difficulties determining what's going wrong after that.

I've double checked that my markdown file anchors are correctly labelled by previewing in ReText (the anchors work as long as I keep the WebKit preview box unchecked). (I'm also aware of the HTML naming requirement as mentioned in this question).

The main difference I see between my implementation and what they're doing is that I'm using QTextBrowser.setMarkdown to populate my markdown preview widget. Does anyone know if this messes with the way that QTextBrowser sets the anchors?

Sample code follows:

import PySide2 as ps2

class App(ps2.QtWidgets.QMainWindow):
    def __init__(self, parents=None):
        self.ui.textBrowser.anchorClicked.connect(self.on_anchorClicked)

    def read_file(self, file_path):
        file_handle = ps2.QtCore.QFile(file_path.absoluteFilePath())
        if not file_handle.open(ps2.QtCore.QFile.ReadOnly | ps2.QtCore.QFile.Text):
            return False

        stream = ps2.QtCore.QTextStream(file_handle)
        self.ui.textBrowser.setMarkdown(stream.readAll())
    
    def on_anchorClicked(self, link):
        url = link.url()
        if url.startswith("#"):
            print("Attempting to scroll to anchor {}".format(url[1:]))
            self.ui.textBrowser.scrollToAnchor(url[1:])
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
wliu
  • 11
  • 1

0 Answers0