【发布时间】:2021-09-22 00:00:03
【问题描述】:
我正在创建一个在文件中绘制数据的应用程序。绘制的第一个文件定义了所有其他数据相对于转换的原点。 AFAICT,QFileDialog 总是按字母顺序返回文件,无论选择顺序如何。
有没有办法返回按选择排序的数据?
为了说明,创建一个文件夹,其中包含名为 A、B、C 或 1、2、3 的文件。无论它们被选择或出现在文件名行编辑中的方式如何,返回的路径列表均按字母顺序排列.
import os
import sys
from PyQt5 import QtCore, QtWidgets
MYDIR = (os.environ['USERPROFILE'] + '/Desktop/numbered').replace("\\", "/")
def on_button_pressed():
paths, _ = QtWidgets.QFileDialog.getOpenFileNames(
directory = MYDIR,
caption='Open',
filter=(
'All (*.*)'
))
for i, path in enumerate(paths):
print(i, path, flush=True)
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
button = QtWidgets.QPushButton("Open")
button.pressed.connect(on_button_pressed)
button.show()
sys.exit(app.exec_())
编辑可能会挂起的@musicamate 响应的实现:
import os
import sys
from PyQt5 import QtCore, QtWidgets
MYDIR = (os.environ['USERPROFILE'] + '/Desktop/numbered').replace("\\", "/")
class SelectionOrderFileDialog(QtWidgets.QFileDialog):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.setOption(QtWidgets.QFileDialog.DontUseNativeDialog)
self.setFileMode(QtWidgets.QFileDialog.ExistingFiles)
self.setWindowFlags(self.windowFlags() & ~QtCore.Qt.WindowContextHelpButtonHint)
list_view = self.findChild(QtWidgets.QListView, 'listView')
self.selection_model = list_view.selectionModel()
self.selection_model.selectionChanged.connect(self.check_selection)
self.current_selection = []
def check_selection(self):
active_selection = []
for index in self.selection_model.selectedRows():
path = index.data(QtWidgets.QFileSystemModel.FilePathRole)
active_selection.append(path)
updated_current_selection = []
for path in self.current_selection:
if path in active_selection:
updated_current_selection.append(path)
active_selection.remove(path)
updated_current_selection.extend(active_selection)
self.current_selection[:] = updated_current_selection
print(self.current_selection, flush=True)
def on_button_pressed():
# Works fine when called as...
# dialog = SelectionOrderFileDialog()
# Causes hangs on Open
dialog = SelectionOrderFileDialog(
directory = MYDIR,
caption='Open',
filter=(
'text (*.txt)'
';;python (*.py)'
';;All (*.*)'
))
dialog.exec_()
if __name__ == '__main__':
app = QtWidgets.QApplication(sys.argv)
button = QtWidgets.QPushButton("Open")
button.resize(300, 25)
button.pressed.connect(on_button_pressed)
button.show()
sys.exit(app.exec_())
【问题讨论】:
-
可能不会。不要让他们一次选择多个文件,而是要求他们一次选择一个文件。然后,您可以在每次选择文件时将它们添加到全局列表中,并按照它们选择的顺序保留它们。
-
这是个好建议。
-
可以做到,但不能使用静态方法:您需要创建一个 QFileDialog 实例,根据您的需要对其进行配置并与
filesSelected信号连接并实现一个“保持”的方法选择更改时的排序。 -
@musicamante 即使是原生对话?
-
@LoremIpsum 你是什么意思?