在文本编辑框中添加图片,需要借助QTextDocument把图片作为资源添加到QTextEdit中

  1. The QTextDocument class holds formatted text that can be viewed and edited using a QTextEdit.  
  2.  
  3. QTextDocument is a container for structured rich text documents,  
  4.  
  5. A QTextDocument can be edited programmatically using a QTextCursor,   

两种方法

第一个:通过URL自愿形式

 
  
  1. QTextEdit *editor=new QTextEdit;     
  2.  
  3.  this->editor->append("<img src=/"1.png/n  //通过URL来插入到editor中  
  4.  

第二个:通过QTextImageFormat,利用QTextCursor来插入到文本编辑中

 
  
  1. QTextImageFormat p_w_picpathFormat;   //保存图片格式对象  
  2.     p_w_picpathFormat.setName("1.png");  
  3.     QTextCursor cursor;                         //编辑指针标  
  4.     cursor.insertImage(p_w_picpathFormat);   //通过编辑指针表把图片格式的文件插入到资源中  
  5.  
  6.    
  7.  

 把图片添加到资源缓存中

 

QT中也给了个的Demo,有时间可以去看看。

 
  
  1. QApplication app(argc,argv);  
  2.  
  3.    
  4.  
  5.        QTextCodec::setCodecForCStrings(QTextCodec::codecForName("System"));  
  6.  
  7.        QTextCodec::setCodecForTr(QTextCodec::codecForName("System"));  
  8.  
  9.        QTextCodec::setCodecForLocale(QTextCodec::codecForName("System"));  
  10.  
  11.    
  12.  
  13.        QString  s = tt();     
  14.  
  15.        int width=QApplication::desktop()->width();   
  16.  
  17.        int height=QApplication::desktop()->height();   
  18.  
  19.        QTextEdit *edit = new QTextEdit();  
  20.  
  21.    
  22.  
  23.        edit->setText(s);  
  24.  
  25.         edit->append("<img src='//Program Files//helloQT//1.png'>");  
  26.  
  27.        edit->setReadOnly(true);  
  28.  
  29.        edit->resize(200,200);  
  30.  
  31.        edit->show();  
  32.  
  33.        app.exec();  
  34.  

 

 
  
  1. QTextDocument *document=new QTextDocument(this);  //图片容器  
  2.     QUrl url;  
  3.     url = QUrl::fromLocalFile("1.png");   //指定Url  
  4.     document->addResource(QTextDocument::ImageResource,url,QVariant(url));  //添加资源到document容器中  
  5.