例子
以下示例演示了调用文件对话框的两种方法。
第一个按钮通过静态方法调用文件对话框。
fname = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\',"Image files (*.jpg *.gif)")
选定的图像文件显示在标签小部件上。第二个按钮通过调用 QFileDialog 对象的 exec_() 方法来调用文件对话框。
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.AnyFile)
dlg.setFilter("Text files (*.txt)")
filenames = QStringList()
if dlg.exec_():
filenames = dlg.selectedFiles()
所选文件的内容显示在 TextEdit 小部件中。
f = open(filenames[0], 'r')
with f:
data = f.read()
self.contents.setText(data)
完整的代码如下 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class filedialogdemo(QWidget):
def __init__(self, parent = None):
super(filedialogdemo, self).__init__(parent)
layout = QVBoxLayout()
self.btn = QPushButton("QFileDialog static method demo")
self.btn.clicked.connect(self.getfile)
layout.addWidget(self.btn)
self.le = QLabel("Hello")
layout.addWidget(self.le)
self.btn1 = QPushButton("QFileDialog object")
self.btn1.clicked.connect(self.getfiles)
layout.addWidget(self.btn1)
self.contents = QTextEdit()
layout.addWidget(self.contents)
self.setLayout(layout)
self.setWindowTitle("File Dialog demo")
def getfile(self):
fname = QFileDialog.getOpenFileName(self, 'Open file',
'c:\\',"Image files (*.jpg *.gif)")
self.le.setPixmap(QPixmap(fname))
def getfiles(self):
dlg = QFileDialog()
dlg.setFileMode(QFileDialog.AnyFile)
dlg.setFilter("Text files (*.txt)")
filenames = QStringList()
if dlg.exec_():
filenames = dlg.selectedFiles()
f = open(filenames[0], 'r')
with f:
data = f.read()
self.contents.setText(data)
def main():
app = QApplication(sys.argv)
ex = filedialogdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
上面的代码产生以下输出 -
exec_() 方法的完整代码如下 -
import sys
from PyQt5.QtCore import *
from PyQt5.QtGui import *
from PyQt5.QtWidgets import *
class CustomDialog(QFileDialog):
def __init__(self, *args, **kwargs):
super(CustomDialog, self).__init__(*args, **kwargs)
self.setWindowTitle("HELLO!")
QBtn = QDialogButtonBox.Ok | QDialogButtonBox.Cancel
self.buttonBox = QDialogButtonBox(QBtn)
self.buttonBox.accepted.connect(self.accept)
self.buttonBox.rejected.connect(self.reject)
self.layout = QVBoxLayout()
self.layout.addWidget(self.buttonBox)
self.setLayout(self.layout)
class filedialogdemo(QWidget):
def __init__(self, parent = None):
super(filedialogdemo, self).__init__(parent)
layout = QVBoxLayout()
self.btn1 = QPushButton("QFileDialog object")
self.btn1.clicked.connect(self.getfiles)
layout.addWidget(self.btn1)
self.contents = QTextEdit()
layout.addWidget(self.contents)
self.setLayout(layout)
self.setWindowTitle("File Dialog demo")
def getfiles(self, s):
print("click", s)
dlg = CustomDialog(self)
if dlg.exec_():
filenames = dlg.selectedFiles()
f = open(filenames[0], 'r')
with f:
data = f.read()
self.contents.setText(data)
def main():
app = QApplication(sys.argv)
ex = filedialogdemo()
ex.show()
sys.exit(app.exec_())
if __name__ == '__main__':
main()
上面的代码产生以下输出 -
所选文件中的文本将显示在 TextEdit 控件中。