第一步:
PyQt4 Designer设计程序界面
该部分设计类同Visval Studio内的设计,改下各部件的objectName!
设计完保存为editor.ui
第二步:
将.ui文件编译成.py文件
cmd.exe
cd 到改文件所在的文件夹
然后输入pyuic4 editor.ui > editor.py
第三步:
新建start.py,输入程序:
import sys
from PyQt4 import QtCore, QtGui #调用库函数
from editor import Ui_notepad
from PyQt4 import QtCore, QtGui #调用库函数
from editor import Ui_notepad
class StartQt4(QtGui.QMainWindow):
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_notepad()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog) #open按钮被点击后跳到自定义函数file_dialog
QtCore.QObject.connect(self.ui.button_save,QtCore.SIGNAL("clicked()"), self.file_save)
def __init__(self, parent=None):
QtGui.QWidget.__init__(self, parent)
self.ui = Ui_notepad()
self.ui.setupUi(self)
QtCore.QObject.connect(self.ui.button_open,QtCore.SIGNAL("clicked()"), self.file_dialog) #open按钮被点击后跳到自定义函数file_dialog
QtCore.QObject.connect(self.ui.button_save,QtCore.SIGNAL("clicked()"), self.file_save)
def file_dialog(self):
fd = QtGui.QFileDialog(self)
self.filename = fd.getOpenFileName() #getOpenFileName()函数 “打开”
from os.path import isfile
if isfile(self.filename):
s = open(self.filename,'r').read()
self.ui.editor_window.setPlainText(s)
fd = QtGui.QFileDialog(self)
self.filename = fd.getOpenFileName() #getOpenFileName()函数 “打开”
from os.path import isfile
if isfile(self.filename):
s = open(self.filename,'r').read()
self.ui.editor_window.setPlainText(s)
def file_save(self):
fd = QtGui.QFileDialog()
self.filename =fd.getSaveFileName() #getSaveFileName()函数 “另存为”
fobj =open(self.filename,'w')
fobj.write(self.ui.editor_window.toPlainText())
fobj.close()
self.ui.editor_window.setText('File saved!!')
fd = QtGui.QFileDialog()
self.filename =fd.getSaveFileName() #getSaveFileName()函数 “另存为”
fobj =open(self.filename,'w')
fobj.write(self.ui.editor_window.toPlainText())
fobj.close()
self.ui.editor_window.setText('File saved!!')
if __name__ == "__main__":
app = QtGui.QApplication(sys.argv)
myapp = StartQt4()
myapp.show()
sys.exit(app.exec_())
第四步:编译
相关截图如下:
1.程序编译后的出现的界面
2. open file 读文件
3.save file 保存文件
4.保存成功
ok,study more...