前言

在初始化QWidget时出现了以下问题。

Traceback (most recent call last):
  File "form/__init__.py", line 62, in __init__
    self.setupUi(self)
  File "view/form.py", line 31, in setupUi
    QtCore.QMetaObject.connectSlotsByName(Form)
SystemError: <built-in function connectSlotsByName> returned a result with an error set

正文

# view/form.py
# 文件由 pyuic5 生成。
class Ui_Form(object):
    def setupUi(self, Form):
        # 其它初始化代码
        QtCore.QMetaObject.connectSlotsByName(Form)
# form/__init__.py
from view.form import Ui_Form

class Form(Ui_Form, QWidget):
    def __init__(self, path: str = None):
        super().__init__()
        self.setupUi(self)
        self._path = path

    @property
    def path(self):
        return self._path

这段代码表面上没有问题,但在断点调试中发现,当调用Ui_Form - setupUi中的QtCore.QMetaObject.connectSlotsByName(Form)时,会访问self的所有属性(含property所装饰的方法)。

那么问题就很明显了,self.path属性对应的变量self._path未被初始化,被调用则会出错。

# form/__init__.py
from view.form import Ui_Form

class Form(Ui_Form, QWidget):
    def __init__(self, path: str = None):
        super().__init__()
        self._path = path
        self.setupUi(self)

    @property
    def path(self):
        return self._path

问题解决。