简体   繁体   中英

Check if user clicked bolded text in QTextBrowser?

I'm making an app that shows lyrics for songs from Genius.com website and now I'm implementing a feature that lets user see the annotations for the lyrics as well but I don't know how to check if the user clicked the annotation in my QTextBrowser (annotations are bolded withtags). Is there anything I can do to detect the click on a specific text like setToolTip() method does?

If you want to detect if the pressed text is bold or not, then you must override the mousePressEvent method to obtain the position, and with it obtain the QTextCursor that contains that information:

import sys
from PyQt5 import QtGui, QtWidgets


class TextBrowser(QtWidgets.QTextBrowser):
    def mousePressEvent(self, event):
        super().mousePressEvent(event)
        pos = event.pos()
        tc = self.cursorForPosition(pos)
        fmt = tc.charFormat()
        if fmt.fontWeight() == QtGui.QFont.Bold:
            print("text:", tc.block().text())


if __name__ == "__main__":
    app = QtWidgets.QApplication(sys.argv)
    w = TextBrowser()

    html = """
    <!DOCTYPE html>
        <html>
            <body>

            <p>This text is normal.</p>
            <p><b>This text is bold.</b></p>
            <p><strong>This text is important!</strong></p>
            <p><i>This text is italic</i></p>
            <p><em>This text is emphasized</em></p>
            <p><small>This is some smaller text.</small></p>
            <p>This is <sub>subscripted</sub> text.</p>
            <p>This is <sup>superscripted</sup> text.</p>
            </body>
        </html>
    """

    w.insertHtml(html)

    w.resize(640, 480)
    w.show()
    sys.exit(app.exec_())

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