PyQt5 多文件路径选择与显示 - 使用 QFileDialog 和 QLineEdit
以下是一个示例代码,可以设置多个文件的存储路径,并将路径显示在 lineEdit 中:
from PyQt5.QtWidgets import QApplication, QFileDialog, QLineEdit, QMainWindow, QVBoxLayout, QWidget, QPushButton
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
self.file_paths = []
central_widget = QWidget()
layout = QVBoxLayout()
self.line_edit = QLineEdit()
layout.addWidget(self.line_edit)
select_files_button = QPushButton('Select Files')
select_files_button.clicked.connect(self.select_files)
layout.addWidget(select_files_button)
central_widget.setLayout(layout)
self.setCentralWidget(central_widget)
def select_files(self):
options = QFileDialog.Options()
options |= QFileDialog.DontUseNativeDialog
file_names, _ = QFileDialog.getOpenFileNames(self, 'Select Files', '', 'All Files (*);;Text Files (*.txt)', options=options)
if file_names:
self.file_paths = file_names
self.line_edit.setText('
'.join(file_names))
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
在这个示例中,我们创建了一个 MainWindow 类,其中包含一个 lineEdit 和一个 'Select Files' 按钮。当用户单击按钮时,将打开文件对话框以选择文件,并将所选文件的路径存储在 file_paths 列表中。然后,我们使用 join() 方法将这些路径连接成一个字符串,并将其显示在 lineEdit 中。
请注意,我们使用了 QFileDialog.getOpenFileNames() 方法以打开多个文件对话框,并且使用了使用 '\n' 分隔符将路径连接起来的方法。您可以根据需要更改这些选项,例如使用 QFileDialog.getOpenFileName() 方法以打开单个文件对话框。
原文地址: https://www.cveoy.top/t/topic/mqpn 著作权归作者所有。请勿转载和采集!