I am migrating a codebase of PyQt5 to PyQt6. I read the stackoverflow question another user asked:
Migrating to Qt6/PyQt6: what are all the deprecated short-form names in Qt5?
My question is simply a variation of this, ie, in my case I've spent several hours trying to find the longer form for the following:
def flags(self, index: QModelIndex) -> Qt.QFlags:
return Qt.ItemIsDropEnabled | Qt.ItemIsEnabled | Qt.ItemIsEditable | Qt.ItemIsSelectable | Qt.ItemIsDragEnabled
Error received:
AttributeError: type object 'Qt' has no attribute 'ItemFlags'.
Previously I've been able to figure out the long-form equivalent required in Qt6, but in this case I can't figure it out. (When this one is solved, I will probably have to find the equivalence for the return values in the code example above: Qt.ItemIsDropEnabled, etc.)
I would have been happy to have posted this in the form of a comment under the other posted question, but stackoverflow says I need 50 reputation pts to comment.
The "flags" (plural form) refers to the combination of enum values, which instead refer to each single value (see the documentation).
As written in the comment of the answer you linked, the PyQt maintainer seems to be very resistant to any "shorter" solution, and he chose to always use the Enum namespace for Python consistence even for flags, and even if some Qt enum/flag names are not consistent for backward compatibility; this might be very confusing, not to mention the fact that this obviously means even longer code lines (and we all know how we already struggle with the length of Qt object names).
To clarify, here's a typical and confusing case (in Qt terms, and valid with PyQt5):
Qt.AlignCenter
is a Qt::AlignmentFlag
, but its actually an enum (even if it's named "flag"); see the result for PyQt5: >>> test = Qt.AlignCenter
>>> print(type(test))
<class 'PyQt5.QtCore.Qt.AlignmentFlag'>
>>> print(test)
132
Qt.AlignHCenter|Qt.AlignVCenter
results in a Qt::Alignment
, but it's actually a flag, even if it's actually equal to Qt.AlignCenter
: >>> test = Qt.AlignHCenter|Qt.AlignVCenter
>>> print(type(test))
<class 'PyQt5.QtCore.Alignment'>
>>> print(test)
<PyQt5.QtCore.Alignment object at 0xb30ff41c>
>>> print(int(test))
132
In any case, the point remains: if you want to use a value, you must use the enum namespace, which is Qt.ItemFlag
without the trailing "s".
def flags(self, index: QModelIndex) -> Qt.QFlags:
return (
Qt.ItemFlag.ItemIsDropEnabled
| Qt.ItemFlag.ItemIsEnabled
| Qt.ItemFlag.ItemIsEditable
| Qt.ItemFlag.ItemIsSelectable
| Qt.ItemFlag.ItemIsDragEnabled
)
Remember to always refer to the official C++ API documentation of classes and objects in order to understand the different types and get their proper names: none of the Python docs are good for that, both PyQt and "Qt for Python" (aka, PySide).