You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何将指定QML窗口UI保存为PDF?

指定QML窗口抓取并导出PDF的解决方案

步骤1:给QML窗口设置唯一标识

在你需要抓取的第二个QML窗口中,设置objectName属性作为唯一识别标识:

Window {
    objectName: "secondWindow" // 这个名字要和调用screenShot时传入的winid参数一致
    // 窗口其他内容...
}

步骤2:修改C++代码,匹配指定窗口

修改screenShot函数,通过传入的winid匹配对应窗口的objectName,只对目标窗口进行抓取和PDF导出:

void PdfExporter::screenShot(QString path, QString winid)
{
    foreach(QObject* obj, mEngine->rootObjects()) 
    {
        QQuickWindow* window = qobject_cast<QQuickWindow*>(obj);
        // 只处理objectName匹配且可见的窗口
        if (window && window->objectName() == winid && window->isVisible())
        {
            QImage image = window->grabWindow();

            QPrinter printer;
            printer.setOutputFormat(QPrinter::PdfFormat);
            printer.setOutputFileName(path + "/Report.pdf");

            QPainter painter(&printer);
            QRect rect = painter.viewport();
            QSize size = image.size();

            size.scale(rect.size(), Qt::KeepAspectRatio);
            painter.setViewport(rect.x(), rect.y(), size.width(), size.height());
            painter.setWindow(image.rect());

            painter.drawImage(QRect(0, 0, image.width(), image.height()), image);
        }
    }
}

关键说明

  • 通过objectName匹配窗口,精准定位到目标窗口,避免遍历所有窗口执行导出操作。
  • 添加窗口可见性判断,防止窗口未显示时抓取到空白图像。
  • 移除了代码中无用的window->renderTargetId()调用和重复设置的输出格式,简化逻辑。

内容的提问来源于stack exchange,提问作者Praveenkumar Thulasiraman

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.07 00:22:47