【问题标题】:Check if user clicked bolded text in QTextBrowser?检查用户是否单击了 QTextBrowser 中的粗体文本?
【发布时间】:2020-10-30 13:47:25
【问题描述】:

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

【问题讨论】:

    标签: python python-3.x pyqt pyqt5 qtextbrowser


    【解决方案1】:

    如果要检测按下的文本是否为粗体,则必须重写 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_())
    

    【讨论】:

    • 我可以在继承自QMainWindow 的类中覆盖这个函数吗?这是我的代码:hastebin.com/ukikisacob.rb
    • @Kiren78 为什么要覆盖另一个任务的类的方法?除了看起来很可怕之外,一个简单的解决方案是复制我的类并将行更改为:self.textBrowser = TextBrowser(self)
    • 谢谢,我还能检查已单击文本的内容,以将正确的注释与文本匹配吗?
    • @Kiren78 我不知道你说的注解是什么意思,我猜你想把粗体文本压下来,对吗?
    • 我想检查点击了哪些文本,例如(来自屏幕截图)“Twoja koleżanka też na dole,没有前戏(哦)”。我想检查是否单击了此行或其他行并阅读其内容。对不起,我很不擅长解释事情。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-07-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多