'How to paint object by overriding paintEvent in Qt?

In my QGraphicsView, I have many QGraphicsItem. I want to search specific QGraphicsItem out of all the items present in view and highlight the matched item. For highlighting item, I am trying to use paintEvent.

So I am calling paintEvent, but not understanding how to heighlight border of the matched object ?
Should I need co-ordinates of that matched object ?

I tried like this:

  foreach(QGraphicsItem* currentItem, _scene->items())
        {
            pEvent = false;
            QGraphicsRectItem* rItem = qgraphicsitem_cast<QGraphicsRectItem*>(currentItem);
            if(rItem)
            {
                // some logic to get i->Name()
                QString name1 = i->Name();
                QString name2 = "reN"; // I want to find reN named item in view
                
                if(name1 == name2)
                {
                    pEvent = true;
                    qDebug()<<"Object Found ";
                    this->repaint();
                    break;
                }
            }
        }      
       

    void myClass::paintEvent(QPaintEvent *event) {
        Q_UNUSED(event);
        qDebug()<<"In paint event ";
        if(pEvent)
        {
            QPainter qp(this);
            drawBody(&qp);
        } 
    }
    
    void myClass::drawBody(QPainter *qp) {
        Q_UNUSED(qp);
        // want logic for heighlighting border of the item
}       
      


Solution 1:[1]

I understand from your problem that you are overridng QGraphicsView in MyClass since paintEnent is defined QWidgets classes.

To solve your problem, if I understand correctly. It's necessary to save the QGraphicsRectItem coordinates:

QRectF rectF = item.boundingRect();

then use the following in the function drawBody:

qp.save();
const float width = 5;
QPen pen;
pen.setWidth(width );
pen.setColor("green");
painter->drawRect(rectF.x(), rectF().y(), 
rectF().width(), rectF().height());
qp.restore();

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 svirid