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

How to access a QGraphicsItem's state in paint event via the option parameter?



  • Hi!
    I have a working C++ code snippet where I check for a QGraphicsItem placed in a QGraphicsScene whether the mouse is hovering over it:

    void ParameterPin::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
    {
        Q_UNUSED(widget);
    
        QPen pen = QPen(QBrush(QColor(150, 150, 150)), 2);
        QBrush brush = QBrush(_color);
    
        if(option->state & QStyle::State_MouseOver) {
            brush.setColor(_color.lighter());
        }
    
        // Point
        painter->setPen(pen);
        painter->setBrush(brush);
    
        painter->drawEllipse(0, 0, 15, 15);
    }
    
    

    The option parameter is of QStyleOptionGraphicsItem class which according to the docs inherits from QStyleOption. QStyleOption has a state variable which is a state enum representing different states including the MouseOver state.

    For some reason, the same code shown above doesn't work with PySide2. The PySide2 documentation is uncomplete there and I can't find a way to accomplish the same. Any suggestions?

    An approach like this:

                if option.state and QStyle.State_MouseOver:
                    color = color.lighter()
    

    always returns true.
    Thanks for answers!


  • Lifetime Qt Champion

    Hi,

    & and "and" are not the same operation. You need the former which is a "bitwise and".


  • Lifetime Qt Champion

    Hi,

    & and "and" are not the same operation. You need the former which is a "bitwise and".



  • @Niagarer
    As @SGaist has said. Just so you know when reading C++ code, it is && in C++ which equates to Python and. Single & C++ operator is same as Python's &.



  • @SGaist oh my goodness, totally, thank you so much!


Log in to reply