我正在尝试围绕我已经拥有的一些代码构建一个 GUI。我了解如何在手动构建 GUI 时执行此操作,但是在将其添加到由 Qt Designer 和 pyuic 生成的 python 代码时被卡住了。举个例子,我可能需要一个按钮,它允许用户指向一个文件,我手动这样做,这很有效:
import sys
from PyQt4 import QtGui
class Example(QtGui.QWidget):
def __init__(self):
super(Example, self).__init__()
self.initUI()
def initUI(self):
btn = QtGui.QPushButton('Open File', self)
btn.setToolTip('This is a <b>QPushButton</b> widget')
btn.resize(btn.sizeHint())
btn.move(50, 50)
btn.clicked.connect(self.loadFile)
self.setGeometry(300, 300, 250, 150)
self.show()
def loadFile(self):
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
# some custom code for reading file and storing it
def main():
app = QtGui.QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
但是,当我尝试在 Qt Designer 代码中执行相同操作时,程序会在到达文件对话框之前停止。
from PyQt4 import QtCore, QtGui
try:
_fromUtf8 = QtCore.QString.fromUtf8
except AttributeError:
def _fromUtf8(s):
return s
try:
_encoding = QtGui.QApplication.UnicodeUTF8
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig, _encoding)
except AttributeError:
def _translate(context, text, disambig):
return QtGui.QApplication.translate(context, text, disambig)
class Ui_Form(object):
def setupUi(self, Form):
Form.setObjectName(_fromUtf8("Form"))
Form.resize(400, 300)
self.pushButton = QtGui.QPushButton(Form)
self.pushButton.setGeometry(QtCore.QRect(130, 100, 75, 23))
self.pushButton.setObjectName(_fromUtf8("pushButton"))
self.retranslateUi(Form)
QtCore.QObject.connect(self.pushButton, QtCore.SIGNAL(_fromUtf8("clicked()")), self.loadFile)
QtCore.QMetaObject.connectSlotsByName(Form)
def retranslateUi(self, Form):
Form.setWindowTitle(_translate("Form", "Form", None))
self.pushButton.setText(_translate("Form", "Open File", None))
def loadFile(self):
print('loadFile1')
fname = QtGui.QFileDialog.getOpenFileName(self, 'Open file', '/home')
print('loadFile2')
if __name__ == "__main__":
import sys
app = QtGui.QApplication(sys.argv)
Form = QtGui.QWidget()
ui = Ui_Form()
ui.setupUi(Form)
Form.show()
sys.exit(app.exec_())
这只会打印 loadFile() 中的第一条语句,但不会打开文件对话框窗口。我究竟做错了什么?