Search code examples
qtqt5qgraphicssceneqgraphicsitemqpainter

Storing the results of QPainter rendering into a QPixmap instance


I want to apply blur effect to a gradient generated by GRadialGradient and rendered by QPainter.Looks like for such graphical effects I have to provide a pixmap and a QGraphicsScene and then call the ->render() method but I couldn't find any ways to add a QPainter directly into any subclass of QGraphicsItem.

So is there any way to do that?
I think converting the QPainter render results to QPixmap can solve the problem.But I don't know how.And I don't know how the performance of converting then applying the blur effect in real-time would be.

Here's an excerpt from what I've written so far:

void MainWindow::paintEvent(QPaintEvent *event){
    Q_UNUSED(event);

    QRadialGradient grad(QPoint(this->width()/2,this->height()/2) , 50);
    grad.setSpread(QGradient::RepeatSpread);
    grad.setColorAt(0 , QColor(0,0,0));
    grad.setColorAt(1 , QColor(100,100,100));
    QPainter paint(this);

    paint.setRenderHint(QPainter::Antialiasing , true);

    QRectF r1(0,0,this->width(),this->height());

    paint.drawRect(r1);
    QBrush brush(grad);
    paint.fillRect(r1 , brush);
...
...
}

And here's the results:

enter image description here

Thanks.


Solution

  • Your question is clearly an XY problem, instead of asking about the underlying problem: How to display a QGraphicsItem that shows the circular gradient + blur effect, questions about an attempted solution: convert to QPixmap.

    In this case, the simplest thing is to use a QGraphicsRectItem where you set the gradient as brush and the effect is applied to that item:

    QGraphicsBlurEffect *effect = new QGraphicsBlurEffect(this);     
    effect->setBlurRadius(100);
    
    QRadialGradient grad(QPoint(50, 50), 50);
    grad.setSpread(QGradient::RepeatSpread);
    grad.setColorAt(0 , QColor(0, 0, 0));
    grad.setColorAt(1 , QColor(100, 100, 100));
    
    QGraphicsRectItem *item = new QGraphicsRectItem(0, 0, 100, 100); 
    item->setBrush(QBrush(grad));
    item->setGraphicsEffect(effect);