Mypy issues when both PyQt5 and PyQt6 are installed

I’ve been having issues getting Qt code to type-check correctly since the move to Qt6, but never bothered to look into this deeply until now.

Take the following code for example:

from typing import TYPE_CHECKING

from aqt.qt import *

if TYPE_CHECKING or qtmajor > 5:
    from ..forms.form_qt6 import Ui_Dialog
else:
    from ..forms.form_qt5 import Ui_Dialog  # type: ignore

dialog = QDialog()
form = Ui_Dialog()
form.setupUi(dialog)
item = QListWidgetItem("hello", form.listWidget)
form.listWidget.addItem(item)

When both pyqt5 and pyqt6 are installed in the environment (both needed to compile .ui forms), mypy emits spurious errors like the “call-overload” error in the QListWidgetItem line.

The following patch to main fixes the issue, but it breaks type checking when only pyqt5 is installed:

diff --git a/qt/aqt/qt/__init__.py b/qt/aqt/qt/__init__.py
index d3b1c7914..dd7b28ce3 100644
--- a/qt/aqt/qt/__init__.py
+++ b/qt/aqt/qt/__init__.py
@@ -7,12 +7,13 @@
 import os
 import sys
 import traceback
-from typing import Callable, TypeVar, Union
+from typing import Callable, TypeVar, Union, TYPE_CHECKING

 try:
     import PyQt6
 except:
-    from .qt5 import *  # type: ignore
+    if not TYPE_CHECKING:
+        from .qt5 import *  # type: ignore
 else:
     if not os.getenv("DISABLE_QT5_COMPAT"):
         print("Running with temporary Qt5 compatibility shims.")

Does anyone have a better solution?

One option would be to munge the Qt6 output into a format suitable for use with Qt5, like what Anki’s build_ui.py does.

1 Like

This topic was automatically closed 30 days after the last reply. New replies are no longer allowed.