PDA

View Full Version : How to display image on QPlainTextEdit



naoyamakino
14th July 2009, 23:30
Hi there, I am looking for a way to display image(emoticons) on QPlainTextEdit.
here is what I have done so far; this class is called by a QWidget class


import sys
from PyQt4 import QtGui
from PyQt4 import QtCore

class TextView(QtGui.QPlainTextEdit):
def __init__(self,Ui_MainWindow, parent=None):
QtGui.QPlainTextEdit.__init__(self, parent)
self.setReadOnly(True)

cursor = self.textCursor()
cursor.movePosition(QtGui.QTextCursor.NextWord, QtGui.QTextCursor.KeepAnchor)
cursor.insertText("test")

self.setTextCursor(cursor)

imageCursor = self.textCursor()
imageCursor.movePosition(QtGui.QTextCursor.NextWor d, QtGui.QTextCursor.KeepAnchor)

icon = QtGui.QPixmap("image/emoticon.png")
image = icon.toImage()
if image.isNull():
print 'null'
imageCursor.insertImage(image)
self.setTextCursor(imageCursor)

now it only displays "text" but not the image. What am I doing wrong? is there any ways to display image or icon onto QPlainTextEdit?

I would appreciate advice if anyone has encountered this or a similar issue.

wysota
15th July 2009, 09:41
You can't do that... that's why it's called plaintext edit. Use QTextEdit or QTextBrowser instead.

naoyamakino
15th July 2009, 15:44
thank you for your reply, wysota. yes that works!!
here is my code for anyone who had a similar problem.


class TextView(QtGui.QTextEdit):
def __init__(self,Ui_MainWindow, parent=None):
QtGui.QTextEdit.__init__(self, parent)
self.setReadOnly(True)
self.setAcceptRichText(True)
def insert(self, string,emoticonList):
cursor = self.textCursor()
if not emoticonList:
cursor.insertText(string)
else:
ls = shlex.split(str(string))
for word in ls:
for emoticon in emoticonList[:]:
if word == emoticon:
path = "image/emoticons/" + word
icon = QtGui.QPixmap(path)
image = icon.toImage()
cursor.insertImage(image)
else:
cursor.insertText(word + " ")
self.setTextCursor(cursor)
end = "<br>"
fragment = QtGui.QTextDocumentFragment.fromHtml(end)
self.textCursor().insertFragment(fragment)
def insertReceiveMessage(self, msg):
cursor = self.textCursor()
cursor.insertText(msg)
self.setTextCursor(cursor)
end = "<br>"
fragment = QtGui.QTextDocumentFragment.fromHtml(end)
self.textCursor().insertFragment(fragment)

thank you so much, wysota!