-
Notifications
You must be signed in to change notification settings - Fork 4
/
FileDialogDelegateQt.py
55 lines (46 loc) · 1.98 KB
/
FileDialogDelegateQt.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
""" FileDialogDelegateQt.py: Delegate that pops up a file dialog when double clicked.
Sets the model data to the selected file name.
"""
import os.path
try:
from PyQt5.QtCore import Qt, QT_VERSION_STR
from PyQt5.QtWidgets import QStyledItemDelegate, QFileDialog
except ImportError:
try:
from PyQt4.QtCore import Qt, QT_VERSION_STR
from PyQt4.QtGui import QStyledItemDelegate, QFileDialog
except ImportError:
raise ImportError("FileDialogDelegateQt: Requires PyQt5 or PyQt4.")
__author__ = "Marcel Goldschen-Ohm <marcel.goldschen@gmail.com>"
class FileDialogDelegateQt(QStyledItemDelegate):
""" Delegate that pops up a file dialog when double clicked.
Sets the model data to the selected file name.
"""
def __init__(self, parent=None):
QStyledItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
""" Instead of creating an editor, just popup a modal file dialog
and set the model data to the selected file name, if any.
"""
pathToFileName = ""
if QT_VERSION_STR[0] == '4':
pathToFileName = QFileDialog.getOpenFileName(None, "Open")
elif QT_VERSION_STR[0] == '5':
pathToFileName, temp = QFileDialog.getOpenFileName(None, "Open")
pathToFileName = str(pathToFileName) # QString ==> str
if len(pathToFileName):
index.model().setData(index, pathToFileName, Qt.EditRole)
index.model().dataChanged.emit(index, index) # Tell model to update cell display.
return None
def displayText(self, value, locale):
""" Show file name without path.
"""
try:
if QT_VERSION_STR[0] == '4':
pathToFileName = str(value.toString()) # QVariant ==> str
elif QT_VERSION_STR[0] == '5':
pathToFileName = str(value)
path, fileName = os.path.split(pathToFileName)
return fileName
except:
return ""