[PyKDE] Solved: Re: Inserting Rich Text in a QTextEdit
Michael Sparks
zathras at thwackety.com
Tue Dec 21 03:16:06 GMT 2004
On Mon, 20 Dec 2004, Michael Sparks wrote:
> I've been using a QTextEdit for a while as a simple rich text editor, and
> recently been playing with various ideas and have hit a bit of a block.
> Essentially what I want to do is this:
>
[ question wanting
editor.insert("<a href='"+str(page)+"'>"+str(page)+"</a>" )
to actually insert that as rich text (ie add the tags as tags) rather
than interpreted as plain text ]
OK, in case the silence was "no idea" (I did a bunch of web searches that
came up blank - both before and after posing the q) I've settled on this
approach which works:
if editor.hasSelectedText():
text = editor.selectedText()
editor.removeSelectedText()
else:
text = page
editor.setUpdatesEnabled( 0)
q=editor.getCursorPosition()
editor.append("<a href='"+str(page)+"'>"+str(text)+"</a>" )
paraCount = editor.paragraphs()
print editor.paragraphLength(paraCount-1)
editor.setSelection(paraCount-1,0,paraCount-1, editor.paragraphLength(paraCount-1))
editor.cut()
editor.setCursorPosition(*q)
editor.paste()
editor.setUpdatesEnabled( 1)
editor.updateContents()
Context:
I have an edittable drop down which may contain either page names or URLs.
When the user selects one (or types in a new page name or URL), the
current section is used as the link text, and page name/URL used as the
link target. If there isn't a current selection, the page name/URL is used
as the link text.
I suppose you could generalise this as:
def insertRichText(editor, someText):
if editor.hasSelectedText():
text = editor.selectedText()
editor.removeSelectedText()
else:
text = page
editor.setUpdatesEnabled( 0)
q=editor.getCursorPosition()
editor.append(str(someText))
paraCount = editor.paragraphs()
print editor.paragraphLength(paraCount-1)
editor.setSelection(paraCount-1,0,paraCount-1, editor.paragraphLength(paraCount-1))
editor.cut()
editor.setCursorPosition(*q)
editor.paste()
editor.setUpdatesEnabled( 1)
editor.updateContents()
If you use a custom stylesheet, this should also mean that you can use
this approach for inserting anything into the current position in the
document.
Michael.
More information about the PyQt
mailing list