我使用的是python 2.7版本,并在python中使用pyqt4进行GUI编程。我想从Ui_MainWindow1
致电Ui_MainWindow2
。这是代码:
班级Ui_MainWindow1
class Ui_MainWindow1(object):
def setupUi(self, MainWindow):
...
...
self.pushButton = QtGui.QPushButton(self.centralwidget)
self.pushButton.setGeometry(QtCore.QRect(70, 90, 181, 27))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
MainWindow.setCentralWidget(self.centralwidget)
...
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"),self.callSecondWindow)
def callSecondWindow(self):
MainWindow2 = QtGui.QMainWindow()
ui = Ui_MainWindow2()
ui.setupUi(MainWindow2)
MainWindow2.show()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
MainWindow = QtGui.QMainWindow()
ui = Ui_MainWindow1()
ui.setupUi(MainWindow)
MainWindow.show()
sys.exit(app.exec_())
Ui_MainWindow2
class Ui_MainWindow2(object):
def setupUi(self, MainWindow):
MainWindow.setObjectName(_fromUtf8("MainWindow"))
MainWindow.resize(336, 277)
self.centralwidget = QtGui.QWidget(MainWindow)
self.centralwidget.setObjectName(_fromUtf8("centralwidget"))
self.label = QtGui.QLabel(self.centralwidget)
self.label.setGeometry(QtCore.QRect(110, 70, 131, 51))
font = QtGui.QFont()
...
...
当我点击pushButton
中的Ui_MainWindow1
时。它没有显示另一个GUI(Ui_MainWindow2
)并且没有给出任何错误。
如何解决这个问题?需要帮忙!
答案 0 :(得分:1)
看起来很乱。这是编写类似内容的更常见方式:
from PyQt4 import QtGui
from PyQt4.uic.properties import QtCore
class MainWindow1(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow1, self).__init__(*args, **kwargs)
self.pushButton = QtGui.QPushButton('pushButton')
self.pushButton.released.connect(self.callSecondWindow)
self.mainWindow2 = MainWindow2()
self.setCentralWidget(self.pushButton)
def callSecondWindow(self):
self.mainWindow2.show()
class MainWindow2(QtGui.QMainWindow):
def __init__(self, *args, **kwargs):
super(MainWindow2, self).__init__(*args, **kwargs)
self.resize(336, 227)
self.setObjectName('centralwidget')
self.label = QtGui.QLabel()
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
mainWindow = MainWindow1()
mainWindow.show()
sys.exit(app.exec_())
一些注意事项:
不需要setupUi
函数python已经有__init__
信号语法:
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL("clicked()"),self.callSecondWindow)
已被更具可读性的self.pushButton.released.connect(self.callSecondWindow)
通常没有理由在一个额外的对象中保存QMainWindow
的实例,只是直接将其子类化
大多数人对变量使用小写名称,为类使用大写名称,这只是一种约定,但它使代码对其他人更具可读性