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

2024-06-06 14:06:16 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个显示Genius.com网站歌曲歌词的应用程序,现在我正在实现一个功能,让用户也可以看到歌词的注释,但我不知道如何检查用户是否在我的QTextBrowser中单击了注释(注释用标记加粗)。我能做些什么来检测像setToolTip()方法那样的对特定文本的点击吗


Tags: 方法用户标记文本功能com应用程序网站
1条回答
网友
1楼 · 发布于 2024-06-06 14:06:16

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

相关问题 更多 >