0

假设 QTextEdit 中有文本和图像。假设您提取 QTextEdit 的 HTML 代码。现在如何在 HTML 代码中找到图像被实例化的位置 () 并替换为我作为 QImage 对象保留前图像的位置和大小的另一个图像。

换句话说,当第二张图片作为QImage存储在程序中时,需要在保留第一张图片的位置和大小的同时交换图片。

请考虑第一个图像可能根本不存在。无论是否存在类似file://path/to/image/image_name.png的图像,都可以人为地将 HTML 代码设置为 QTextEdit 。

4

1 回答 1

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);
于 2010-12-14T11:49:52.513 回答