PDA

View Full Version : Drag and drop image into a QTextEdit ?



balazsbela
2nd September 2007, 13:29
I am trying to be able to drag and drop images from files into a QTextEdit and display them in it.
I subclassed QTextEdit reimplemented dropEvent and it sort of works, the right url of image is used, when I open the resulting document(saved from the QTextEdit in html) in firefox the image gets displayed, but in my QTextEdit only an image icon is displayed, not the image.
Also after I drag and drop the image the cursor stops blinking.

Here is the code:



void CQTextEdit::dragEnterEvent(QDragEnterEvent *event)
{
event->acceptProposedAction();
}

void CQTextEdit::dropEvent(QDropEvent *e)
{
if (e->mimeData()->hasFormat("text/uri-list"))
{
journalImage = &qvariant_cast<QImage>(e->mimeData()->imageData());
QTextCursor cursor = this->textCursor();
QTextDocument *document = this->document();
cursor.movePosition(QTextCursor::Right,QTextCursor ::MoveAnchor,this->toPlainText().size());
document->addResource(QTextDocument::ImageResource,e->mimeData()->urls()[0],journalImage);
cursor.insertImage(e->mimeData()->urls()[0].toString());
this->setHtml(this->toHtml());

}
else QTextEdit::dropEvent(e);
}


journalImage is a pointer to a QImage.
Part of the code was inspired from the docs:
http://doc.trolltech.com/4.3/qtextedit.html
Which I also tried to use, but with not too much luck.
Can anyone help me ?

jpn
3rd September 2007, 14:47
The key to success seems to be reimplementing QTextEdit::canInsertFromMimeData() and QTextEdit::insertFromMimeData(). See wiki: Drop images on QTextEdit (http://wiki.qtcentre.org/index.php?title=Drop_images_on_QTextEdit) for more details.