[英]Check if user clicked bolded text in QTextBrowser?
我正在制作一個應用程序,顯示來自 Genius.com 網站的歌曲的歌詞,現在我正在實現一個功能,讓用戶也可以看到歌詞的注釋,但我不知道如何檢查用戶是否點擊了注釋在我的 QTextBrowser 中(注釋以粗體顯示標簽)。 我能做些什么來檢測對特定文本的點擊,比如setToolTip()
方法嗎?
如果要檢測按下的文本是否為粗體,則必須重寫 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.