我想圍繞我已經有的一些代碼構建GUI。我瞭解如何在手動構建GUI時執行此操作,但在將此代碼添加到由Qt Designer和pyuic生成的python代碼時,我會陷入困境。舉個例子,我可能需要一個按鈕,這將允許用戶指向一個文件,該文件手動我一樣如此,這一點也適用:PyQt與定製插槽的作品,Qt設計器不
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()中的第一條語句,但不打開文件對話框窗口。我究竟做錯了什麼?
(1)閱讀生成文件頂部的註釋:'#警告!此文件中所做的所有更改都將丟失!'。 (2)閱讀PyQt文檔:[使用Qt設計器](http://pyqt.sourceforge.net/Docs/PyQt4/designer.html)。 (3)在可顯示Python追溯的環境中運行代碼。 – ekhumoro