QFileDialog
QFileDialog是一个让用户选择文件和目录的对话框,可用以选择打开或保存文件
# -*- coding: utf-8 -*-
"""
PyQt5 tutorial
In this example, we determine the event sender
object.
author: py40.com
last edited: 2017年3月
"""
import sys
from PyQt5.QtWidgets import (QMainWindow, QTextEdit,
QAction, QFileDialog, QApplication)
from PyQt5.QtGui import QIcon
class Example(QMainWindow):
def __init__(self):
super().__init__()
self.initUI()
def initUI(self):
self.textEdit = QTextEdit()
self.setCentralWidget(self.textEdit)
self.statusBar()
openFile = QAction(QIcon('open.png'), 'Open', self)
openFile.setShortcut('Ctrl+O')
openFile.setStatusTip('Open new File')
openFile.triggered.connect(self.showDialog)
menubar = self.menuBar()
fileMenu = menubar.addMenu('&File')
fileMenu.addAction(openFile)
self.setGeometry(300, 300, 350, 300)
self.setWindowTitle('File dialog')
self.show()
def showDialog(self):
fname = QFileDialog.getOpenFileName(self, 'Open file', '/home')
if fname[0]:
f = open(fname[0], 'r')
with f:
data = f.read()
self.textEdit.setText(data)
if __name__ == '__main__':
app = QApplication(sys.argv)
ex = Example()
sys.exit(app.exec_())
使用QtDesign方法:
这里面叫你如何覆盖生成的文件处理方法:pyuic
简略记录下,防止那个博主网站没了:
三、实现程序
应该来说我们只要在上边的“PyQT_Form.py”中,将需要的包导入—添加pushButton_click()函数实现代码----实例化Ui_Form类,实现这三步程序应该就差不多了
但是PyQT_Form.py是PyUIC文件按照“PyQT_Form.ui”生成的,如果我们需要去调整PyQT_Form.ui(比如调整按钮位置调整文本框大小,后续调整界面在实际编程中基本是必然需求)
调整完后重新生成PyQT_Form.py时,PyUIC可不会管当前我们已经在PyQT_Form.py中写了什么代码,旧PyQT_Form.py会直接被新PyQT_Form.py覆盖
也就是说,所有逻辑代码我们都不应当写入PyQT_Form.py文件(或者叫不要动PyQT_Form.py文件),我们新建一个文件在里边创建一个子类(MyPyQT_Form)继承PyQT_Form.py中的Ui_Form
3.1 实现代码
在项目中新建一个.py文件,写入如下代码
复制代码
import sys
from PyQt5 import QtWidgets
from PyQT_Form import Ui_Form
class MyPyQT_Form(QtWidgets.QWidget,Ui_Form):
def __init__(self):
super(MyPyQT_Form,self).__init__()
self.setupUi(self)
#实现pushButton_click()函数,textEdit是我们放上去的文本框的id
def pushButton_click(self):
self.textEdit.setText("你点击了按钮")
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
my_pyqt_form = MyPyQT_Form()
my_pyqt_form.show()
sys.exit(app.exec_())
这里继承可能会出错,只要把PyQT_Form中的UI_From类中的类似:
MainWindow.setStatusBar(self.statusbar)
注释掉就行