Qt TextEdit 中添加图片的几种方法(转)
2011-07-24 21:23:44| 分类: QT | 标签: |字号大中小 订阅
(1)I think this is a very simple question, but when I copy an p_w_picpath I can't paste it in a QTextEdit? Paste is inactive! Also I would like to know how to drag-and-drop a picture.
BTW I use the following code in order to insert a picture into a QTextEdit:
QTextEdit *textEditor = new QTextEdit(0);
QTextDocumentFragment fragment;
fragment = QTextDocumentFragment::fromHtml("<img src='C:\\aaa.jpg'>");
textEditor->textCursor().insertFragment(fragment);
textEditor->setVisible(true);
(2)
void TextEdit::insertImage()
{
QString file = QFileDialog::getOpenFileName(this, tr("Select an p_w_picpath"),
".", tr("Bitmap Files (*.bmp)\n"
"JPEG (*.jpg *jpeg)\n"
"GIF (*.gif)\n"
"PNG (*.png)\n"));
QUrl Uri ( QString ( "file://%1" ).arg ( file ) );
QImage p_w_picpath = QImageReader ( file ).read();
QTextDocument * textDocument = m_textEdit->document();
textDocument->addResource( QTextDocument::ImageResource, Uri, QVariant ( p_w_picpath ) );
QTextCursor cursor = m_textEdit->textCursor();
QTextImageFormat p_w_picpathFormat;
p_w_picpathFormat.setWidth( p_w_picpath.width() );
p_w_picpathFormat.setHeight( p_w_picpath.height() );
p_w_picpathFormat.setName( Uri.toString() );
cursor.insertImage(p_w_picpathFormat);
}
(3)The third way is to inherit QTextEdit and reimplement bool canInsertFromMimeData(const QMimeData* source) const and void insertFromMimeData(const QMimeData* source) functions as followes. Buy the way this method allows to use drag-and-drop or copy-paste mechanisms.
class TextEdit : public QTextEdit
{
public:
bool canInsertFromMimeData(const QMimeData* source) const
{
return source->hasImage() || source->hasUrls() ||
QTextEdit::canInsertFromMimeData(source);
}
void insertFromMimeData(const QMimeData* source)
{
if (source->hasImage())
{
static int i = 1;
QUrl url(QString("dropped_p_w_picpath_%1").arg(i++));
dropImage(url, qvariant_cast<QImage>(source->p_w_picpathData()));
}
else if (source->hasUrls())
{
foreach (QUrl url, source->urls())
{
QFileInfo info(url.toLocalFile());
if (QImageReader::supportedImageFormats().contains(info.suffix().toLower().toLatin1()))
dropImage(url, QImage(info.filePath()));
else
dropTextFile(url);
}
}
else
{
QTextEdit::insertFromMimeData(source);
}
}
private:
void dropImage(const QUrl& url, const QImage& p_w_picpath)
{
if (!p_w_picpath.isNull())
{
document()->addResource(QTextDocument::ImageResource, url, p_w_picpath);
textCursor().insertImage(url.toString());
}
}
void dropTextFile(const QUrl& url)
{
QFile file(url.toLocalFile());
if (file.open(QIODevice::ReadOnly | QIODevice::Text))
textCursor().insertText(file.readAll());
}
};
Just wanted to share what I find during long investigation :).
转的别人的 第二种试过了,可以用