2013-12-22 20 views
1

我已经在Qt中创建了一个接口作为.ui文件,然后将其转换为python文件。然后,我想为组件添加一些功能,例如单选按钮等。为此,我尝试从Qt重新实现类并添加我的事件。但它提供了以下错误:如何重新实现由Qt生成的Ui_MainWindow

self.radioButton_2.toggled.connect(self.radioButton2Clicked) 
NameError: name 'self' is not defined 

我的第一个问题是,这是否是对付使用Qt生成的类正确/合适的方法是什么?其次,为什么我会得到错误?

我的代码是在这里:

import sys 
from PySide import QtCore, QtGui 
from InterfaceClass_Test01 import Ui_MainWindow 

class MainInterface(QtGui.QMainWindow, Ui_MainWindow): 
    def __init__(self, parent=None): 
     super(MainInterface, self).__init__(parent) 
     self.ui = Ui_MainWindow() 
     self.ui.setupUi(self) 

    def setupUi(self, MainWindow): 
     super(MainInterface, self).setupUi(parent, MainWindow) 

     self.radioButton.toggled.connect(self.radioButtonClicked) 
     self.radioButton_2.toggled.connect(self.radioButton2Clicked) 
     self.radioButton_3.toggled.connect(self.radioButton3Clicked) 

    def radioButton3Clicked(self, enabled): 
     pass 

    def radioButton2Clicked(self, enabled): 
     pass 

    def radioButtonClicked(self, enabled): 
     pass 

回答

1

生成的文件都有点不直观。 UI类只是一个简单的包装,并不是Qt Designer的顶级小部件的子类(如您所期望的那样)。

取而代之,UI类有一个setupUi方法,它接收顶级类的实例。此方法将添加Qt Designer中的所有小部件,并将它们的实例属性(通常为self)。属性名称取自Qt Designer中的objectName属性。将由Qt给出的默认名称重置为更易读的名称是个好主意,以便稍后可以很容易地引用它们。 (不要忘记重新生成UI模块你做出更改后!)

是进口的UI应该结束了寻找这样的模块:

import sys 
from PySide import QtCore, QtGui 
from InterfaceClass_Test01 import Ui_MainWindow 

class MainInterface(QtGui.QMainWindow, Ui_MainWindow): 
    def __init__(self, parent=None): 
     super(MainInterface, self).__init__(parent) 
     # inherited from Ui_MainWindow 
     self.setupUi(self) 
     self.radioButton.toggled.connect(self.radioButtonClicked) 
     self.radioButton_2.toggled.connect(self.radioButton2Clicked) 
     self.radioButton_3.toggled.connect(self.radioButton3Clicked) 

    def radioButton3Clicked(self, enabled): 
     pass 

    def radioButton2Clicked(self, enabled): 
     pass 

    def radioButtonClicked(self, enabled): 
     pass 
+0

谢谢!是的,它解决了问题!一个问题:MainInterface类有2个参数,这意味着它有2个父母!那么,如何在使用超级方法运行时知道哪个__init__被调用? –

+1

'MainInterface'类没有两个父母:它从两个基类继承。 [super](http://docs.python.org/2/library/functions.html#super)调用确保所有基类(和_their_基类等)的__init__被调用正确的顺序。 – ekhumoro