pyside2 文件列表过滤格式
时间: 2023-10-08 07:12:52 浏览: 67
要实现在PySide2中加载指定格式的文件列表,可以使用QFileDialog来获取文件路径,但是需要在文件选择对话框中设置文件类型过滤器,以便只选择指定格式的文件。可以使用setFileMode()方法设置为QFileDialog.ExistingFiles模式,以允许选择多个文件。
下面是一个示例代码:
```python
import os
from PySide2.QtWidgets import QApplication, QMainWindow, QFileDialog, QTableWidget, QTableWidgetItem
class MainWindow(QMainWindow):
def __init__(self):
super().__init__()
# 创建表格控件
self.table = QTableWidget()
self.table.setColumnCount(2)
self.table.setHorizontalHeaderLabels(['文件名', '文件大小'])
self.setCentralWidget(self.table)
# 添加菜单
menu_bar = self.menuBar()
file_menu = menu_bar.addMenu('文件')
open_action = file_menu.addAction('打开')
open_action.triggered.connect(self.open_files)
def open_files(self):
# 设置文件类型过滤器
file_filter = '文本文件 (*.txt);;所有文件 (*.*)'
# 获取文件路径列表
file_paths, _ = QFileDialog.getOpenFileNames(self, '打开文件', '.', file_filter, options=QFileDialog.DontUseNativeDialog)
# 清空表格
self.table.setRowCount(0)
# 遍历文件列表,添加到表格中
for file_path in file_paths:
# 判断文件类型是否符合要求
if file_path.endswith('.txt'):
file_name = os.path.basename(file_path)
file_size = os.path.getsize(file_path)
row_count = self.table.rowCount()
self.table.insertRow(row_count)
self.table.setItem(row_count, 0, QTableWidgetItem(file_name))
self.table.setItem(row_count, 1, QTableWidgetItem(str(file_size)))
if __name__ == '__main__':
app = QApplication([])
window = MainWindow()
window.show()
app.exec_()
```
在这个示例程序中,我们添加了一个文件过滤器,并使用QFileDialog.getOpenFileNames()方法获取文件路径列表。我们还使用了QFileDialog.DontUseNativeDialog选项,以确保在所有平台上的文件过滤器都能正常工作。然后,我们遍历文件列表,只将以".txt"结尾的文件添加到表格中。