您的位置:首页 > 编程语言 > Qt开发

QT 中QTextEdit添加图片 .

2012-05-05 13:10 232 查看
在文本编辑框中添加图片,需要借助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 imageFormat;   //保存图片格式对象
imageFormat.setName("1.png");
QTextCursor cursor;                         //编辑指针标
cursor.insertImage(imageFormat);   //通过编辑指针表把图片格式的文件插入到资源中

把图片添加到资源缓存中

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容器中
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  图片 QTextEdit