此问题已存在here,但答案似乎已过时或不再适用于Python 2.7。
当我使用此代码子类化我的QFileDialog时,会调用FileDialog类init,但从不调用openClicked方法。
class FileDialog(QtGui.QFileDialog):
def __init__(self, *args):
QtGui.QFileDialog.__init__(self, *args)
self.setOption(self.DontUseNativeDialog, True)
self.setFileMode(self.ExistingFiles)
btns = self.findChildren(QtGui.QPushButton)
self.openBtn = [x for x in btns if 'open' in str(x.text()).lower()][0]
self.openBtn.clicked.disconnect()
self.openBtn.clicked.connect(self.openClicked)
self.tree = self.findChild(QtGui.QTreeView)
def openClicked(self):
inds = self.tree.selectionModel().selectedIndexes()
files = []
for i in inds:
if i.column() == 0:
files.append(os.path.join(str(self.directory().absolutePath()),str(i.data().toString())))
self.selectedFiles = files
self.hide()
def filesSelected(self):
return self.selectedFiles
这是对FileDialog的正确调用吗?
mydialog = FileDialog()
filelist = mydialog.getExistingDirectory(self, "Select Stuff", "", QtGui.QFileDialog.DontConfirmOverwrite)
答案 0 :(得分:2)
另一个问题的解决方案不必要地复杂化。您需要做的只是覆盖QFileDialog.accept()
,然后您可以自由地实现您喜欢的任何行为。
以下示例非常简单。它不会检查所选文件(例如查看它们是否仍然存在),但如果需要,可以轻松添加。
from PyQt4 import QtCore, QtGui
class FileDialog(QtGui.QFileDialog):
def __init__(self, *args, **kwargs):
super(FileDialog, self).__init__(*args, **kwargs)
self.setOption(QtGui.QFileDialog.DontUseNativeDialog, True)
self.setFileMode(QtGui.QFileDialog.ExistingFiles)
def accept(self):
super(FileDialog, self).accept()
class Window(QtGui.QWidget):
def __init__(self):
super(Window, self).__init__()
self.button = QtGui.QPushButton('Test', self)
self.button.clicked.connect(self.handleButton)
layout = QtGui.QVBoxLayout(self)
layout.addWidget(self.button)
def handleButton(self):
dialog = FileDialog()
if dialog.exec_() == QtGui.QDialog.Accepted:
print(dialog.selectedFiles())
if __name__ == '__main__':
import sys
app = QtGui.QApplication(sys.argv)
window = Window()
window.show()
sys.exit(app.exec_())