0

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 with tags). Is there anything I can do to detect the click on a specific text like setToolTip() method does?

Zephyr
  • 11,891
  • 53
  • 45
  • 80
Kiren78
  • 55
  • 9

1 Answers1

1

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_())
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • Can I overwrite this function in a class that inherits from `QMainWindow`? Here is my code: https://hastebin.com/ukikisacob.rb – Kiren78 Jul 09 '20 at 23:04
  • @Kiren78 Why do you want to override the method of a class whose task is another? In addition to looking horrible, a simple solution is to copy my class and change the line to: `self.textBrowser = TextBrowser(self)` – eyllanesc Jul 09 '20 at 23:13
  • Thanks and can I also check the contents of the text that has been clicked to match the correct annotation to the text? – Kiren78 Jul 10 '20 at 15:49
  • @Kiren78 I don't know what you mean by annotation, I guess you want to get the bold text pressed, am I correct? – eyllanesc Jul 10 '20 at 16:02
  • I want to check what text was clicked e.g. (from the screenshot) "Twoja koleżanka też na dole, no foreplay (ooh)". I want to check if this line was clicked or the other and read its content. I'm quite bad at explaining things sorry. – Kiren78 Jul 10 '20 at 16:35
  • So can I do it? If you understood what I want to do. – Kiren78 Jul 13 '20 at 15:41