Introduction
I often take Qt namespace for granted, it became
a natural habit of setting a Qt parameter using Qt namespace, for instance:
setting alignment for a QStandardItem
1 | item = QtGui.QStandardItem('test') |
Here, the Qt.AlignRight
is an AlignmentFlag
Enum type object which has a
value of 0x0002
or 2
, which creates the behavior of aligning with the right edge.
Now, let’s try parsing the alignment of the QStandardItem
again, using:
1 | align = item.textAlignment() |
this returns a PyQt5.QtCore.Alignment
object, which we don’t really
know the value of. And also note that it is not a AlignmentFlag
object like
previously.
So, What’s the difference between these two, and how should I retrieve the namespace value?
QEnum
and QFlags
QFlags is used to store combinations of Enum, which provides type checking safety.
thus, Alignment
QFlags type is simply a typedef for AlignmentFlag
QEnum.
Qt.AlignmentFlag
is QEnum type;AlignmentFlag
being the enum nameQt.Alignment
is QFlags type;Alignment
being the type name- there’s also non-flag enums, which have the same type and enum name
Example
Declaration of both object types
1 | # <class 'PyQt5.QtCore.AlignmentFlag'> |
As we can see, setAlignment()
takes a Qt.Alignment parameter
, which means that any
combination of Qt.AlignmentFlag
values, or int
, is legal.
1 | item = QtGui.QStandardItem('test') |
The return value is QFlags type, but it can be cast to an integer type to reveal its Enum value
1 | # <class 'PyQt5.QtCore.Alignment'> |
Parse Namespace and Value Mapping
Still not sure what the Enum value means?
We can either check the docs, or use this to print out a mapping of the namespace and its corresponding value
1 | def enum_mapping(cls, enum): |