Python qt: bitwise operations

From wikinotes

Many of Qt options are set with binary numbers, and are operated on using bitwise operators.

Binary in Python

# int to binary
bin(2)           #>> '0b10'  (ignore '0b' prefix)

# binary-str to int
int('0b10', 2)   #>> 2

Bitwise Operators

# check bit
int('0b0011', 2) & int('0b0001', 2)   # >> 1  (1st bit is set)
int('0b0011', 2) & int('0b0010', 2)   # >> 2  (2nd bit is set)
int('0b0011', 2) & int('0b1000', 2)   # >> 0  (4th bit not set)

# set bit
bin(int('0b0011', 2) | int('0b0010', 2))  #>> '0b0011'  (2nd bit already set)
bin(int('0b0011', 2) | int('0b0100', 2))  #>> '0b0111'  (3rd bit gets set)

# unset bit
bin(int('0b111', 2) & ~int('0b010', 2))   #>> '0b101'   (2nd bit gets unset) 

# toggle/flip bit
bin(int('0b0011', 2) ^ int('0b0010', 2))  #>> '0b0001'
bin(int('0b0011', 2) ^ int('0b1000', 2))  #>> '0b1011'

Bitwise Operators in Qt

# has option
if QStyleOption.state & QStyle.State_Enabled:

# does not have option
if (QStyleOption.state & QStyle.State_Enabled) == 0:

# set option
QStyleOption.state | QStyle.State_Enabled

# unset option
QStyleOption.state & ~QStyle.State_Enabled