MyPy complains about Qt.AlignmentFlag
Asked Answered
C

2

7

When I upgrade to PySide6 6.2.2, MyPy starts complaining about Qt.AlignmentFlag. Here's a small example:

from PySide6.QtGui import Qt
from PySide6.QtWidgets import QLabel, QApplication

app = QApplication()
label = QLabel("Hello, World!")
label.setAlignment(Qt.AlignCenter)
label.show()

app.exec()

That still runs fine, but MyPy complains:

$ mypy foo.py 
foo.py:6: error: Argument 1 to "setAlignment" of "QLabel" has incompatible type "AlignmentFlag"; expected "Alignment"
Found 1 error in 1 file (checked 1 source file)
$

OK, I try converting the AlignmentFlag to an Alignment.

from PySide6.QtGui import Qt
from PySide6.QtWidgets import QLabel, QApplication

app = QApplication()
label = QLabel("Hello, World!")
label.setAlignment(Qt.Alignment(Qt.AlignCenter))
label.show()

app.exec()

Again, that runs fine, but MyPy now complains about the constructor.

$ mypy foo.py 
foo.py:6: error: Too many arguments for "Alignment"
Found 1 error in 1 file (checked 1 source file)
$

Could someone please explain how to use Qt.Alignment and Qt.AlignmentFlag?

Childbirth answered 4/12, 2021 at 17:44 Comment(0)
C
2

Until I find a better option, I'm going to assume that someone messed up the type hints in PySide6 6.2.2, and I'll just tell MyPy to ignore it.

from PySide6.QtGui import Qt
from PySide6.QtWidgets import QLabel, QApplication

app = QApplication()
label = QLabel("Hello, World!")
label.setAlignment(Qt.AlignCenter)  # type: ignore
label.show()

app.exec()
Childbirth answered 4/12, 2021 at 17:44 Comment(0)
G
2

Have you tried using Qt.AlignmentFlag.AlignCenter instead of Qt.AlignCenter in the setAlignment function? PySide/PyQt fills that field with the enum value you want at runtime, to have some similarity to how you would do it in C++.

Qt.AlignmentFlag is an enum class and AlignCenter is an enum value.

Guidance answered 27/9, 2022 at 18:51 Comment(2)
Same problem Qt.AlignmentFlag.AlignCenter is of type AlginmentFlag, the method expects "Alignment" type, though a thing to note is, I noticed the issue dissappered using the OP codeCissy
@IyadAhmed Probably another thing PySide does at runtime, I don't know, I've only used PyQtGuidance

© 2022 - 2024 — McMap. All rights reserved.