gpt4 book ai didi

python - 从 pyside/pyqt 中的子部件调用父方法

转载 作者:太空狗 更新时间:2023-10-29 23:59:00 24 4
gpt4 key购买 nike

我正在尝试从子类中调用父类的方法。具体来说,我的父类是一个PySide.QtGui.QMainWindow对象,我的子类是一个PySide.QtGui.QWidget对象;后者被设置为前者的中心部件。我正在尝试将子类中的按钮连接到父类中的方法。这在过去使用 self.parent().method_name 对我有用,但在下面的示例中不起作用,我不明白为什么:

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() 的计算结果为 None,因此没有函数 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()

关于python - 从 pyside/pyqt 中的子部件调用父方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24312425/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com