【问题标题】:Paint a QGraphicsItem to a QImage without needing a scene/view在不需要场景/视图的情况下将 QGraphicsItem 绘制到 QImage
【发布时间】:2012-04-08 21:32:36
【问题描述】:

所以这就是我想要做的 - 使用自定义 QGraphicsItem,我将 QPainter 设置为绘制到 QImage 中,然后将其保存到文件中(或者将 QImage 保留在内存中,直到我需要它)。

我发现的问题是 QGraphicsItem::paint() 仅在 QGraphcsItem 属于场景、场景属于视图且视图和场景未隐藏时才被调用。

这是用于测试目的的项目之外的代码:

MyQGfx Class
void MyQGfx::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
{
    qDebug() << "begin of paint function";
    QRectF rec = boundingRect();

    QImage image(boundingRect().size().toSize(),
                 QImage::Format_ARGB32_Premultiplied);
    image.fill(0);

    // construct a dedicated offline painter for this image
    QPainter imagePainter(&image);
    imagePainter.translate(-boundingRect().topLeft());

    // paint the item using imagePainter
    imagePainter.setPen(Qt::blue);
    imagePainter.setBrush(Qt::green);
    imagePainter.drawEllipse(-50, -50, 100, 100);

    imagePainter.end();


    if(image.save("C://plot.jpg"))
    {
        qDebug() << "written";
    }
    else {
        qDebug() << "not written";
    }
}

MainWindow Class
....
QGraphicsView* view = new QGraphicsView(this);
QGraphicsScene* scene = new QGraphicsScene(this);
view->setScene(scene);

MyQGfx* gfx = new MyQGfx();
scene->addItem(gfx);
gfx->update();
....

这一切都很好,但我不需要视图/场景,因为它会显示在主窗口上 - 有什么办法解决这个问题吗?

【问题讨论】:

  • 我确实只是度过了一段美好的时光……我已经有了其他的场景/视图。我可以利用它来保存 QGraphicsItem。但是,如果有人对我正在做的事情有更好的建议,或者回答其他人可能遇到的需要从 QGraphicsItem 中保存 QItem 并避免需要场景/视图的原始问题,我将保持开放状态正在显示在对话框/主窗口上。
  • 你为什么要在那儿而不是其他任何地方作画?
  • 重新思考后,我什至不需要自定义QGraphicsItem。我只想将它绘制到 QImage 的原因是将其转换为 QPixmap 以在 QCursor 中使用。

标签: qt graphics paint qgraphicsview qimage


【解决方案1】:

你不能创建一个自定义方法来接受一个 QPainter,一幅画在 QImage 上,一幅画在你的项目上吗?

【讨论】:

  • 是的 - 这就是我最终所做的。出于某种原因,我让我的画家仍在绘制图形场景 - 我从来没有把它拿出来,这就是它显示在场景中的原因。我什至不需要自定义 QGraphicsItem ,我假设你想要什么。
猜你喜欢
  • 1970-01-01
  • 2015-07-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-05-11
  • 2011-12-05
  • 1970-01-01
  • 2015-04-17
相关资源
最近更新 更多