[英]QFileDialog as editor for TableView: how to get result?
我使用QFileDialog
作為QTableView
某些列的編輯器。 這基本上可以正常工作(對一些焦點問題進行模運算,請參見此處 ):
class DirectorySelectionDelegate(QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = QFileDialog(parent)
editor.setFileMode(QFileDialog.Directory)
editor.setModal(True)
return editor
def setEditorData(self, editor, index):
val = index.model().data(index, Qt.DisplayRole)
fs = val.rsplit(os.path.sep, 1)
if len(fs) == 2:
bdir, vdir = fs
else:
bdir = "."
vdir = fs[0]
editor.setDirectory(bdir)
editor.selectFile(vdir)
def setModelData(self, editor, model, index):
model.setData(index, editor.selectedFiles()[0])
def updateEditorGeometry(self, editor, option, index):
r = option.rect
r.setHeight(600)
r.setWidth(600)
editor.setGeometry(r)
但是,當關閉編輯器時,我看不到區分Choose
和Cancel
(或失去焦點)的方法,在所有情況下都會調用setEditorData
函數。 我沒有看到從QFileDialog
作為editor
獲取結果的方法,我可以找到的所有示例都使用了我無法訪問的exec_
的返回值。
在setModelData
,看起來您可以在設置模型數據之前檢查編輯器的結果 。 默認情況下,結果為QDialog.Rejected
,並且僅當用戶實際選擇文件時才應更改:
def setModelData(self, editor, model, index):
if editor.result() == QtGui.QDialog.Accepted:
model.setData(index, editor.selectedFiles()[0])
更新 :
經過一些遲來的測試之后,很明顯,無論文件對話如何運行(即使使用exec
),其result
也永遠不會在委托編輯器的上下文中正確重置。 因此,需要一點間接性。 根據QFileDialog.filesSelected的文檔,此信號將始終且僅在接受對話框時發送(即使沒有選定的文件)。 因此,我們可以使用這種機制來強制正確的對話框結果,如下所示:
class DirectorySelectionDelegate(QtGui.QStyledItemDelegate):
def createEditor(self, parent, option, index):
editor = QtGui.QFileDialog(parent)
editor.filesSelected.connect(
lambda: editor.setResult(QtGui.QDialog.Accepted))
...
def setModelData(self, editor, model, index):
print(editor.result())
if editor.result() == QtGui.QDialog.Accepted:
model.setData(index, editor.selectedFiles()[0])
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.