从pyside / pyqt中的子窗口小部件调用父方法 [英] calling a parent method from a child widget in pyside/pyqt
问题描述
我正在尝试从子类中调用父类的方法。具体来说,我的父类是 PySide.QtGui.QMainWindow
对象,我的子类是 PySide.QtGui.QWidget
对象;后者被设定为前者的中心小部件。我正在尝试将子项中的按钮连接到父类中的方法。这在过去使用 self.parent()。method_name
对我有用,但它在下面的示例中不起作用,我不明白为什么:
I'm trying to call a method of a parent class from within a child class. Specifically, my parent class is a PySide.QtGui.QMainWindow
object, and my child class is a PySide.QtGui.QWidget
object; the latter is set to be the central widget of the former. I'm trying to connect a button within the child to a method in the parent class. This has worked for me in the past using self.parent().method_name
, but it doesn't work in the example below and I don't understand why:
import sys
from PySide import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.do_something() #sanity check
self.cw = ChildWidget()
self.setCentralWidget(self.cw)
self.show()
def do_something(self):
print 'doing something!'
class ChildWidget(QtGui.QWidget):
def __init__(self):
super(ChildWidget, self).__init__()
self.button1 = QtGui.QPushButton()
self.button1.clicked.connect(self.do_something_else)
self.button2 = QtGui.QPushButton()
self.button2.clicked.connect(self.parent().do_something)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.button1)
self.layout.addWidget(self.button2)
self.setLayout(self.layout)
self.show()
def do_something_else(self):
print 'doing something else!'
def main():
app = QtGui.QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
这是错误:
self.button2.clicked.connect(self.parent().do_something)
AttributeError: 'NoneType' object has no attribute 'do_something'
推荐答案
你永远不会设置你的 MainWindow
作为 ChildWidget
的父级。
所以 self.parent()
计算结果为无
因此没有函数 do_something
。
You never set your MainWindow
as the parent of your ChildWidget
.
So self.parent()
evaluates to None
and therefore has no function do_something
.
尝试:
import sys
from PySide import QtGui, QtCore
class MainWindow(QtGui.QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.do_something() #sanity check
self.cw = ChildWidget(self)
self.setCentralWidget(self.cw)
self.show()
def do_something(self):
print 'doing something!'
class ChildWidget(QtGui.QWidget):
def __init__(self, parent):
super(ChildWidget, self).__init__(parent)
self.button1 = QtGui.QPushButton()
self.button1.clicked.connect(self.do_something_else)
self.button2 = QtGui.QPushButton()
self.button2.clicked.connect(self.parent().do_something)
self.layout = QtGui.QVBoxLayout()
self.layout.addWidget(self.button1)
self.layout.addWidget(self.button2)
self.setLayout(self.layout)
self.show()
def do_something_else(self):
print 'doing something else!'
def main():
app = QtGui.QApplication(sys.argv)
ex = MainWindow()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
这篇关于从pyside / pyqt中的子窗口小部件调用父方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!