2010-12-11 52 views
0

說在QTextEdit中有文本和圖像。並說你提取QTextEdit的HTML代碼。現在,如何在實例化圖像的HTML代碼中找到位置,並用保留前一圖像位置和大小的QImage對象的另一個圖像進行替換。用QTextEdit中的另一個替換圖像

換句話說,當第二張圖像作爲QImage存儲在程序中時,必須在保留第一張圖像的位置和大小的同時交換圖像。

請認爲第一張圖片可能根本不存在。無論是否存在像file://path/to/image/image_name.png這樣的圖像,HTML代碼可能會被人爲設置爲QTextEdit。

回答

1
//Add images as resources 
for(int i = 0; i < vectorOfImages.size(); i++) 
{ 
    QUrl url(QString("image_%1").arg(i)); 
    textEdit->document()->addResource(QTextDocument::ImageResource, url, vectorOfImages.at(i)); 
} 

//Process the htmlCode that is in QTextEdit. 

int count = 0; 
int pos = 0; 

QRegExp rx("<img src=\".+/>"); 
while ((pos = rx.indexIn(htmlCode, pos)) != -1) 
{ 
    QString strToReplace(QString("<img src=\"image_%1\" />").arg(count)); 
    htmlCode.replace(pos, rx.matchedLength(), strToReplace); 
    pos += rx.matchedLength(); 
    count++; 
} 

textEdit->setText(htmlCode);