【问题标题】:QTextEdit: how to save images inserted with QTextCursor?QTextEdit:如何保存使用 QTextCursor 插入的图像?
【发布时间】:2012-07-08 00:30:31
【问题描述】:

我用 QTextCursor 在 QTextEdit 中插入了几个图像,现在我应该如何保存这整个东西?

我的第一个想法是遍历QTextCursor的所有位置,但是我没有找到合适的接口来使用。

使用示例代码:

QTextCursor cursor = ui->textEdit->textCursor();
cursor.insertImage(QImage ("/secure/Common/Pictures/icons/gimp.svg"));
ui->textEdit->setTextCursor(cursor);

QTextDocument *document = ui->textEdit->document();
QStringList images;
QTextBlock b = document->begin();
while (b.isValid()) {
    for (QTextBlock::iterator i = b.begin(); !i.atEnd(); ++i) {
        QTextCharFormat format = i.fragment().charFormat();
        bool isImage = format.isImageFormat();
        if (isImage)
        {
            images << format.toImageFormat().name();
            qDebug() << document->resource(QTextDocument::ImageResource,
                                           QUrl(format.toImageFormat().name())).toByteArray().size();
        }
    }
    b = b.next();
}

【问题讨论】:

  • 保存对图像的引用是否足够,或者保存的文档必须是独立的?
  • @Slavik81 必须能够被导出..我需要将它们存储在数据库中,或任何其他方式?我认为只要能够插入并从某些数据中恢复就可以了

标签: qt qt4


【解决方案1】:

快速而肮脏的解决方案

只需调用document-&gt;toHtml() 并解析img 标签。

清洁解决方案

遍历文本中的所有QTextFragment

QStringList images;
QTextBlock b = document->begin();
while (b.isValid()) {
    for (QTextBlock::iterator i = b.begin(); !i.atEnd(); ++i) {
        QTextCharFormat format = i.fragment().charFormat();
        bool isImage = format.isImageFormat()
        if (isImage)
            images << format.toImageFormat().name();
    }
    b = b.next();
}

警告:我没有对此进行测试,它甚至可能无法编译。

【讨论】:

  • 它工作了,但是你如何获取 QResource 的数据?文档说The name refers to an entry in the application's resources file.,但是我没有找到获取资源数据的函数
  • 试过这个:QFile fp (":/" + format.toImageFormat().name()); fp.open(QIODevice::ReadOnly); qDebug() &lt;&lt; fp.readAll();,得到空输出; fp.errorString() 是 Unknown error
  • 实际上你得到的不是QResources,而是一种完全不同类型的资源,你应该可以通过document-&gt;resource(QTextDocument::ImageResource, name)访问。
  • 好像是空的,QVariant::toByteArray().size() 返回 0,我把我的代码放在我的问题中
  • 这是因为QVariant::toByteArray 仅在参数为字符串或字节数组时有效。图像资源是QPixmapQImage,具体取决于它们的构造方式,因此请使用value&lt;QPixmap&gt;/value&lt;QImage&gt;。更一般地,您可以使用QVariant::typeName() 找出QVariant 的内容类型。
猜你喜欢
  • 2019-11-08
  • 2020-12-31
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-14
相关资源
最近更新 更多