简体   繁体   English

检查用户是否单击了 QTextBrowser 中的粗体文本?

[英]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 with我正在制作一个应用程序,显示来自 Genius.com 网站的歌曲的歌词,现在我正在实现一个功能,让用户也可以看到歌词的注释,但我不知道如何检查用户是否点击了注释在我的 QTextBrowser 中(注释以粗体显示tags).标签)。 Is there anything I can do to detect the click on a specific text like setToolTip() method does?我能做些什么来检测对特定文本的点击,比如setToolTip()方法吗?

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:如果要检测按下的文本是否为粗体,则必须重写 mousePressEvent 方法以获取 position,并获取包含该信息的 QTextCursor:

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_())

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM