PyQt5 QWidget初始化问题

版权声明:本文为博主原创文章,转载请注明出处。

前言

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

1
2
3
4
5
6
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

正文

1
2
3
4
5
6
# view/form.py
# 文件由 pyuic5 生成。
class Ui_Form(object):
def setupUi(self, Form):
# 其它初始化代码
QtCore.QMetaObject.connectSlotsByName(Form)
1
2
3
4
5
6
7
8
9
10
11
12
# 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未被初始化,被调用则会出错。

1
2
3
4
5
6
7
8
9
10
11
12
# 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

问题解决。

Your browser is out-of-date!

Update your browser to view this website correctly. Update my browser now

×