QTextEdit also supports custom drag and drop behavior. By default, QTextEdit will insert plain text, HTML and rich text when the user drops data of these MIME types onto a document. Reimplement canInsertFromMimeData() and insertFromMimeData() to add support for additional MIME types.
For example, to allow the user to drag and drop an image onto a QTextEdit, you could the implement these functions in the following way:
bool TextEdit::canInsertFromMimeData( const QMimeData *source ) const
{
if (source->hasImage())
return true;
else
return QTextEdit::canInsertFromMimeData(source);
}
We add support for image MIME types by returning true. For all other MIME types, we use the default implementation.
void TextEdit::insertFromMimeData( const QMimeData *source )
{
if (source->hasImage())
{
QImage image = qvariant_cast<QImage>(source->imageData());
QTextCursor cursor = this->textCursor();
QTextDocument *document = this->document();
document->addResource(QTextDocument::ImageResource, QUrl("image"), image);
cursor.insertImage("image");
}
}
We unpack the image from the QVariant held by the MIME source and insert it into the document as a resource.