PyQt 4:setupUi()未绑定方法错误

时间:2012-09-05 08:05:57

标签: python eclipse pyqt4

我开始学习使用PyQt4。我有一个简单的gui窗口我想要展示(没什么特别的)。

以下是代码:

import sys
from PyQt4 import QtGui
from test import Ui_MainWindow

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

if __name__ == "__main__":

    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

但是eclipse正在给我以下错误:

TypeError: unbound method setupUi() must be called with Ui_MainWindow instance
as first argument (got MyForm instance instead)

有什么建议吗?

2 个答案:

答案 0 :(得分:3)

您应该继承Ui_MainWindow

import sys
from PyQt4 import QtGui
from test import Ui_MainWindow

class MyForm(QtGui.QMainWindow, Ui_MainWindow):
   def __init__(self, parent=None):
       QtGui.QWidget.__init__(self, parent)
       self.setupUi(self)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

或者您可以创建Ui_MainWindow实例:

import sys
from PyQt4 import QtGui
from test import Ui_MainWindow

class MyForm(QtGui.QMainWindow):
   def __init__(self, parent=None):
       QtGui.QWidget.__init__(self, parent)
       self.ui = Ui_MainWindow()    #note: instance, not the class
       self.ui.setupUi(self)


if __name__ == "__main__":
    app = QtGui.QApplication(sys.argv)
    myapp = MyForm()
    myapp.show()
    sys.exit(app.exec_())

答案 1 :(得分:0)

正如@Bakuriu所说,你想要

self.ui = Ui_MainWindow()

,而不是

self.ui = Ui_MainWindow

。您当前正在将类本身分配给self.ui,而不是创建该类的实例。因此,调用不是“绑定”到成员,而是未绑定(尝试对整个类进行操作)。