2

例如,如果您刚刚设置

self.textedit.setHtml("<b>Bold text</b>")
htmlCheck=self.textedit.toHtml()

hmtlCheck=

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0//EN" "http://www.w3.org/TR/REC-html40/strict.dtd">
<html><head><meta name="qrichtext" content="1" /><style type="text/css">
p, li { white-space: pre-wrap; }
</style></head><body style=" font-family:'MS Shell Dlg 2'; font-size:8.25pt;   
font-weight:400; font-style:normal;">
<p style=" margin-top:0px; margin-bottom:0px; margin-left:0px; margin-right:0px; 
-qt-block-indent:0; text-indent:0px;"><span style=" font-weight:600;">Bold text</span>
</p>
</body></html>

为什么我不能只从第一行代码中获取我设置的文本?这个,我回来的,对进一步的编辑来说太糟糕了……想象一下,我在里面写了一个更大的文本。我想选择文本并将其加粗,或者列出一个列表,并实时检测超链接......当我的代码周围有这么多垃圾也可以单独工作时,我不知道如何处理它. 而且只有 .toPlainText() 和 .toHtml() 函数……超链接的东西非常简单,我可以只使用 .setText(...) 和 .toPlainText() 并每次运行一个正则表达式www. 和 http。但我也想要一个动态列表功能或粗体,也许,因此不能使用 toPlainText()...

有人对我有好的建议吗?

编辑:这里的这个似乎可以将选定的文本设置为粗体,即使是通过不同的段落:

def setBold(self):
    cur=self.textedit.textCursor()
    if cur.hasSelection():
        font=self.textedit.currentFont()
        font.setWeight(QFont.Bold)
        self.textedit.setCurrentFont(font)
4

1 回答 1

1

You can't get the exact text you set back because that's not what the QTextEditor internally stores. For that reason it's methods are called toHtml and toPlainText and not getHtml, that should emphasize that what is returned is a representation of the editors content, not it's exact internal state.

If you want to interact with the editor, you should do it like described here:

  • use the methods designed to edit the (selected) content
  • use a QTextCursor returned by the editors textCursor() method to change selections or modify/insert text at the cursor
于 2013-08-20T17:05:55.667 回答