1

所以这就是我想要做的 - 使用自定义 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();
....

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

4

1 回答 1

2

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

于 2012-03-25T11:20:49.787 回答