[PyQt] Checking a window's state using '&' is always returning False

Kyle Altendorf sda at fstab.net
Mon Aug 21 22:15:35 BST 2017



On 2017-08-21 16:55, Jayson Kempinger wrote:
> How should I be checking the window state then?  The same comparison
> works well for Qt alignment and Qt modifier keys:
> 
>> if event.modifiers() & Qt.ShiftModifier:
>>     shift = True
>> if event.modifiers() & Qt.ControlModifier:
>>     ctrl = True
> 
> So I assumed I should be checking window state in the same way.
> 
> Jayson
> 
>> On Aug 21, 2017, at 4:49 PM, Kyle Altendorf <sda at fstab.net> wrote:
>> 
>> On 2017-08-21 16:45, Jayson Kempinger wrote:
>> 
>>> I'm using PyQt 5.8 and trying to detect a window's state by comparing 
>>> it to known window states using '&', but every comparison returns 
>>> False.
>>> For example:
>>>> if win.windowState() & Qt.WindowNoState:
>>>> print("normal")
>>>> elif win.windowState() & Qt.WindowMinimized:
>>>> print("minimized")
>>>> elif win.windowState() & Qt.WindowMaximized:
>>>> print("maximized")
>>>> else:
>>>> raise NotImplementedError
>>> However, the comparison is always false (so I hit the exception), 
>>> even though _print(int(win.windowState()), int(Qt.WindowNoState))_ 
>>> shows "0 0".
>> 
>> What is 0 & 0?  0.  Which is False.  :]

You need to be considering the actual values and how to handle them.  
Also, this isn't something where only one can be valid at a time so even 
the if/elif isn't quite right.  A window could certainly be both 
maximized and active.  Maximized and minimized may be a valid 
combination, I'm not certain.  Etc.  So,  something like this would 
better fit the data.

state = win.windowState()

if state == Qt.WindowNoState:
     print('no state')

if state & Qt.WindowMinimized:
     print('minimized')

if state & Qt.WindowMaximized:
     print('maximized')

if state & ~(Qt.WindowMinimized | Qt.WindowMaximized | 
Qt.WindowFullScreen | Qt.WindowActive):
     raise NotImplementedError()

Sure, I get that using == for the first one and & on the others is a bit 
odd, but you are really checking that no flags are set, not that the 
WindowNoState flag is set (no such thing really exists).  Hence the 
difference.

If you look back at window state and keyboard modifiers you'll see that 
you weren't actually treating them the same.  In one case you checked 
the 'none' value and not in the other.  In one case you used elif and 
not in the other.  But, from what I see the two are actually the same 
structure and would be handled the same.

http://doc.qt.io/qt-5/qt.html#WindowState-enum
http://doc.qt.io/qt-5/qt.html#KeyboardModifier-enum

Cheers,
-kyle


More information about the PyQt mailing list