qt 子类调用父类的函数,从pyside / pyqt中的子窗口小部件调用父方法

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()

Here is the error:

self.button2.clicked.connect(self.parent().do_something)

AttributeError: 'NoneType' object has no attribute '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.

Try:

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()

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值