2

我开始学习使用 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)

有什么建议么?

4

2 回答 2

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_())
于 2012-09-05T08:28:32.653 回答
0

正如@Bakuriu 所说,你想要

self.ui = Ui_MainWindow()

, 不是

self.ui = Ui_MainWindow

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

于 2012-09-05T08:31:24.990 回答