在PySide2
中,我有一个自定义的对象:
class ResizeEvent(QObject):
def __init__(self, qresizeevent=None):
...
我希望子窗口小部件在调整其大小并且父窗口小部件接收并处理此事件时发出信号。因此,我在子窗口小部件中定义了Signal
,在父窗口小部件中定义了Slot
,并将它们连接起来:
class ChildWidget(QWidget):
resized = Signal(ResizeEvent)
class ParentWidget(QWidget):
@Slot(ResizeEvent)
def onResized(self, event):
print("onResized", event)
...
...
def __init__(self):
...
self.child.resized.connect(self.onResized)
因此,每次调整子窗口小部件的大小时,父窗口小部件都会收到一个信号,并输出一个字符串“ onResized”,后跟自定义事件对象。但是打印的事件对象是None
,当然以下代码会出错。如果我将一些int
参数而不是ResizeEvent
参数传递到信号中,那么我得到了正确的参数。 QtCore.QResizeEvent
参数也是如此。
似乎我的自定义定义对象无法成功通过信号插槽连接传递。为什么会这样呢?我错过了什么吗?
此处提供了一个简化的可重现示例:
import sys
from PySide2.QtCore import QObject, Signal, Slot
from PySide2.QtWidgets import QApplication, QWidget, QVBoxLayout, QPushButton
class ResizeEvent(QObject):
def __init__(self, qresizeevent=None):
self.size = qresizeevent.size()
self.oldSize = qresizeevent.oldSize()
class ChildWidget(QWidget):
resized = Signal(ResizeEvent)
def resizeEvent(self, event):
super().resizeEvent(event)
self.resized.emit(ResizeEvent(event))
class ParentWidget(QWidget):
def __init__(self):
super().__init__()
self.child = ChildWidget()
self.child.setFixedSize(200,50)
self.button = QPushButton("Increase Size")
self.layout = QVBoxLayout()
self.layout.addWidget(self.child)
self.layout.addWidget(self.button)
self.setLayout(self.layout)
self.child.resized.connect(self.onResized)
self.button.clicked.connect(self.onClicked)
@Slot(bool)
def onClicked(self, checked):
self.child.setFixedSize(self.child.width() + 10, self.child.height() + 10)
@Slot(ResizeEvent)
def onResized(self, event):
print("onResized", event)
if __name__ == "__main__":
app = QApplication()
widget = ParentWidget()
widget.show()
sys.exit(app.exec_())
答案 0 :(得分:1)
继承时,必须调用继承的类的构造函数:
class ResizeEvent(QObject):
def __init__(self, qresizeevent=None):
super(ResizeEvent, self).__init__() # <----
self.size = qresizeevent.size()
self.oldSize = qresizeevent.oldSize()