Qt 在不需要场景/视图的情况下,将QGraphicsItem绘制为QImage
下面是我要做的-使用一个定制的QGraphicsItem,我有我的QPaint设置来绘制一个QImage,然后保存到一个文件中(或者只是将QImage保存在内存中,直到我需要它) 我发现的问题是,只有当QGraphicsItem属于场景、场景属于视图且视图和场景未隐藏时,才会调用QGraphicsItem::paint() 以下是出于测试目的而在我的项目之外编写的代码:Qt 在不需要场景/视图的情况下,将QGraphicsItem绘制为QImage,qt,graphics,paint,qgraphicsview,qimage,Qt,Graphics,Paint,Qgraphicsview,Qimage,下面是我要做的-使用一个定制的QGraphicsItem,我有我的QPaint设置来绘制一个QImage,然后保存到一个文件中(或者只是将QImage保存在内存中,直到我需要它) 我发现的问题是,只有当QGraphicsItem属于场景、场景属于视图且视图和场景未隐藏时,才会调用QGraphicsItem::paint() 以下是出于测试目的而在我的项目之外编写的代码: MyQGfx Class void MyQGfx::paint(QPainter *painter, const QStyle
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();
....
MyQGfx类
void MyQGfx::paint(QPainter*painter,const QStyleOptionGraphicsItem*选项,QWidget*小部件)
{
qDebug()更新();
....
这一切都很好,但我不想要必要的视图/场景,因为它会显示在主窗口上-有什么办法吗?你不能创建一个自定义方法,接受一个QPainter,一个QImage上的一幅画和一个项目上的一幅画吗?我肯定只是有点无聊。我已经有了其他东西的场景/视图。我可以我们必须利用它来保存QGraphicsItem。但是,我会将此项保留为打开状态,以防有人对我正在做的事情有更好的建议,或者回答其他人可能遇到的原始问题,即需要从QGraphicsItem保存一个QItem并避免在对话框/Main窗口上显示场景/视图。您为什么希望我不想在那里画画,也不想在其他地方画画?经过重新思考,我甚至不需要定制的QGraphicsSitem。我只想把它画到QImage上的原因是把它转换成QPixmap,用在QCursor上。是的,这就是我最终要做的。出于某种原因,我让我的画家仍然在Graphicscene上画画——我从来没有把它拿出来,这就是为什么它会这样向现场展示..我甚至不需要定制的QGraphicsItem,我假设你想要的是什么。