What just happened?

The state variable is a bitmask holding the possible states of the item. You can check its value against the values of the QStyle::StateFlag parameter using bitwise operators. In the preceding case, the state variable is checked against the State_Selected parameter. If this flag is set, we use green color for the pen.

The type of state is QFlags<StateFlag>. So, instead of using the bitwise operator to test whether a flag is set, you can use the convenient function testFlag().

Used with the preceding example, it would be as follows:

if (option->state.testFlag(QStyle::State_Selected)) {  

The most important states you can use with items are described in the following table:

State Description

State_Enabled

Indicates that the item is enabled. If the item is disabled, you may want to draw it as grayed out.

State_HasFocus

Indicates that the item has the input focus. To receive this state, the item needs to have the ItemIsFocusable flag set.

State_MouseOver

Indicates that the cursor is currently hovering over the item. To receive this state, the item needs to have the acceptHoverEvents variable set to true.

State_Selected

Indicates that the item is selected. To receive this state, the item needs to have the ItemIsSelectable flag set. The normal behavior would be to draw a dashed line around the item as a selection marker.

 

Besides the state, QStyleOptionGraphicsItem offers much more information about the currently used style, such as the palette and the font used, accessible through the QStyleOptionGraphicsItem::palette and QStyleOptionGraphicsItem::fontMetrics parameters, respectively. If you aim for style-aware items, take a deeper look at this class in the documentation.