在文本编辑框中添加图片,需要借助QTextDocument把图片作为资源添加到QTextEdit中
- The QTextDocument class holds formatted text that can be viewed and edited using a QTextEdit.
- QTextDocument is a container for structured rich text documents,
- A QTextDocument can be edited programmatically using a QTextCursor,
两种方法
第一个:通过URL自愿形式
- QTextEdit *editor=new QTextEdit;
- this->editor->append("<img src=/"1.png/n //通过URL来插入到editor中
第二个:通过QTextImageFormat,利用QTextCursor来插入到文本编辑中
- QTextImageFormat p_w_picpathFormat; //保存图片格式对象
- p_w_picpathFormat.setName("1.png");
- QTextCursor cursor; //编辑指针标
- cursor.insertImage(p_w_picpathFormat); //通过编辑指针表把图片格式的文件插入到资源中
把图片添加到资源缓存中
QT中也给了个的Demo,有时间可以去看看。
- QApplication app(argc,argv);
- QTextCodec::setCodecForCStrings(QTextCodec::codecForName("System"));
- QTextCodec::setCodecForTr(QTextCodec::codecForName("System"));
- QTextCodec::setCodecForLocale(QTextCodec::codecForName("System"));
- QString s = tt();
- int width=QApplication::desktop()->width();
- int height=QApplication::desktop()->height();
- QTextEdit *edit = new QTextEdit();
- edit->setText(s);
- edit->append("<img src='//Program Files//helloQT//1.png'>");
- edit->setReadOnly(true);
- edit->resize(200,200);
- edit->show();
- app.exec();
- QTextDocument *document=new QTextDocument(this); //图片容器
- QUrl url;
- url = QUrl::fromLocalFile("1.png"); //指定Url
- document->addResource(QTextDocument::ImageResource,url,QVariant(url)); //添加资源到document容器中
转载于:https://blog.51cto.com/965678322/853215