Important: Please read the Qt Code of Conduct - https://forum.qt.io/topic/113070/qt-code-of-conduct

QGrachphicsItem can not been hit



  • I meet a strange issue about QGraphicsItem.
    1.I define a custom Rect item which derive from QGraphicsItem and rewrite the boundingRect,shape,paint.

    codes are as follows.

    QRectF CameraRectangleItem::boundingRect() const
    {
        qreal extra = 30.0;
        return QRectF(m_startPoint.x(),m_startPoint.y(),m_width,m_height)
        .normalized()
        .adjusted(-extra,-extra,extra,extra);
        //return QGraphicsRectItem::boundingRect();
    }
    QPainterPath CameraRectangleItem::shape() const
    {
        QPainterPath path;
        path.addRect(m_startPoint.x(),m_startPoint.y(),m_width,m_height);
        return path;
    }
    void CameraRectangleItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        QPen myPen;
        if(this->isSelected())
            myPen.setColor(QColor(0,0,184));
        else
            myPen.setColor(Qt::green);
    
        painter->setPen(myPen);
        painter->setBrush(Qt::transparent);
        painter->drawRect(m_startPoint.x(),m_startPoint.y(),m_width,m_height);
        if(this->m_isDrawFontState)
        {
            QFont font("宋体",20,QFont::Bold,false);
    
            painter->setFont(font);
            painter->drawText(m_startPoint.x(),
                              m_startPoint.y(),
                              MyString::intToString(this->m_index)+":"+MyString::intToString(this->m_actualMatchValue)+"/"+MyString::intToString(this->m_presetMatchValue));
        }
    void CameraRectangleItem::updatePos(QPointF endPoint)
    {
        m_width = endPoint.x() - m_startPoint.x();
        m_height = endPoint.y() - m_startPoint.y();
        //this->update(m_startPoint.x(),m_startPoint.y(),m_width,m_height);
    }
    

    2, in the scene,when the mouse press,add new item to scene,
    3.when the mouse release, I call item's updatePos to update item's width and height.

    it woke fine for the drawing the item.
    here come the issue.
    1.when I click the red zone as the picture shows. the item can not be hit.
    Image 1.png
    2.and then I click the black zone as the picture shows, the item is selected.
    Image 2.png
    3.in the step 2 , I move the item , and release the selection of the item.
    at this time, when I click anywehre of the item ,as the picture shows, it can be hit
    Image 3.png

    any one has any idea on this ? thanks.


Log in to reply