本文整理汇总了Python中PyQt4.QtGui.QDirModel类的典型用法代码示例。如果您正苦于以下问题:Python QDirModel类的具体用法?Python QDirModel怎么用?Python QDirModel使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。
在下文中一共展示了QDirModel类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: flags
def flags(self, index):
"""
Can not remember what this is for
"""
if index.column() == 0: # make the first column checkable
return QDirModel.flags(self, index) | Qt.ItemIsUserCheckable
else:
return QDirModel.flags(self, index)
示例2: __init__
def __init__(self, parent=None):
QDirModel.__init__(self, parent)
self.filter = QDir.AllDirs | QDir.Files | QDir.Drives | QDir.NoDotAndDotDot
self.sortflags = QDir.Name | QDir.DirsFirst | \
QDir.IgnoreCase | QDir.LocaleAware
self.nameFilter = ["*.py", "*.pyw"]
self.setNameFilters(self.nameFilter)
self.setFilter(self.filter)
self.setSorting(self.sortflags)
示例3: FileSystemBrowser
class FileSystemBrowser(QTreeView):
"""simple file system browser, no actions yet"""
def __init__(self):
QTreeView.__init__(self)
self.model = QDirModel()
self.setModel(self.model)
self.setSortingEnabled(True)
i = self.model.index(os.getcwd())
self.scrollTo(i)
self.expand(i)
self.setCurrentIndex(i)
for i in range(self.model.columnCount()):
self.resizeColumnToContents(i)
示例4: __init__
def __init__(self):
QTreeView.__init__(self)
self.model = QDirModel()
self.setModel(self.model)
self.setSortingEnabled(True)
self.setAlternatingRowColors(True)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.setAutoExpandDelay(500)
i = self.model.index(os.getcwd())
self.scrollTo(i)
self.expand(i)
self.setCurrentIndex(i)
for i in range(self.model.columnCount()):
self.resizeColumnToContents(i)
self.connect(self, SIGNAL("doubleClicked(QModelIndex)"), self.itemAction)
self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), self.showContextMenu)
示例5: __init__
def __init__(self, fileBrowser):
QComboBox.__init__(self, fileBrowser)
self._fileBrowser = fileBrowser
self.setAttribute( Qt.WA_MacShowFocusRect, False )
self.setAttribute( Qt.WA_MacSmallSize )
self.setEditable(True)
self.setMinimumContentsLength(1)
self.setSizeAdjustPolicy(QComboBox.AdjustToMinimumContentsLengthWithIcon)
self.lineEdit().setReadOnly( False )
self._completionModel = QDirModel(self.lineEdit())
self._completionModel.setFilter( QDir.AllDirs | QDir.NoDotAndDotDot )
self.lineEdit().setCompleter(QCompleter(self._completionModel,
self.lineEdit()))
#TODO QDirModel is deprecated but QCompleter does not yet handle
#QFileSystemModel - please update when possible.
self._count = 0
# Show popup action
self._showPopupAction = QAction(QIcon(':enkiicons/filtered.png'), "File browser history", self)
self._showPopupAction.setShortcut('Ctrl+H')
core.actionManager().addAction("mNavigation/mFileBrowser/aMenuShow", self._showPopupAction)
self._showPopupAction.triggered.connect(self._onShowPopup)
# reconnected in self.updateComboItems()
self.currentIndexChanged[int].connect(self._onItemSelected)
示例6: __init__
def __init__(self, plugin):
QFrame.__init__(self, core.workspace())
self._mode = None
self.plugin = plugin
from PyQt4 import uic # lazy import for better startup performance
uic.loadUi(os.path.join(os.path.dirname(__file__), "SearchWidget.ui"), self)
self.cbSearch.setCompleter(None)
self.cbReplace.setCompleter(None)
self.cbMask.setCompleter(None)
self.fsModel = QDirModel(self.cbPath.lineEdit())
self.fsModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
self.cbPath.lineEdit().setCompleter(QCompleter(self.fsModel, self.cbPath.lineEdit()))
# TODO QDirModel is deprecated but QCompleter does not yet handle
# QFileSystemodel - please update when possible."""
self.cbSearch.setCompleter(None)
self.pbSearchStop.setVisible(False)
self.pbReplaceCheckedStop.setVisible(False)
self._progress = QProgressBar(self)
self._progress.setAlignment(Qt.AlignCenter)
self._progress.setToolTip(self.tr("Search in progress..."))
self._progress.setMaximumSize(QSize(80, 16))
core.mainWindow().statusBar().insertPermanentWidget(1, self._progress)
self._progress.setVisible(False)
# cd up action
self.tbCdUp = QToolButton(self.cbPath.lineEdit())
self.tbCdUp.setIcon(QIcon(":/enkiicons/go-up.png"))
self.tbCdUp.setCursor(Qt.ArrowCursor)
self.tbCdUp.installEventFilter(self) # for drawing button
self.cbSearch.installEventFilter(self) # for catching Tab and Shift+Tab
self.cbReplace.installEventFilter(self) # for catching Tab and Shift+Tab
self.cbPath.installEventFilter(self) # for catching Tab and Shift+Tab
self.cbMask.installEventFilter(self) # for catching Tab and Shift+Tab
self._closeShortcut = QShortcut(QKeySequence("Esc"), self)
self._closeShortcut.setContext(Qt.WidgetWithChildrenShortcut)
self._closeShortcut.activated.connect(self.hide)
# connections
self.cbSearch.lineEdit().textChanged.connect(self._onSearchRegExpChanged)
self.cbSearch.lineEdit().returnPressed.connect(self._onReturnPressed)
self.cbReplace.lineEdit().returnPressed.connect(self._onReturnPressed)
self.cbPath.lineEdit().returnPressed.connect(self._onReturnPressed)
self.cbMask.lineEdit().returnPressed.connect(self._onReturnPressed)
self.cbRegularExpression.stateChanged.connect(self._onSearchRegExpChanged)
self.cbCaseSensitive.stateChanged.connect(self._onSearchRegExpChanged)
self.tbCdUp.clicked.connect(self._onCdUpPressed)
core.mainWindow().hideAllWindows.connect(self.hide)
core.workspace().currentDocumentChanged.connect(
lambda old, new: self.setVisible(self.isVisible() and new is not None)
)
示例7: __init__
def __init__(self):
QTreeView.__init__(self)
self.model = QDirModel()
self.setModel(self.model)
self.setSortingEnabled(True)
i = self.model.index(os.getcwd())
self.scrollTo(i)
self.expand(i)
self.setCurrentIndex(i)
for i in range(self.model.columnCount()):
self.resizeColumnToContents(i)
示例8: __init__
def __init__(self):
super(GeneralPreferences, self).__init__()
grid = QGridLayout(self)
grid.setSpacing(20)
grid.setColumnStretch(1, 10)
# directory auto completer
completer = QCompleter(self)
dirs = QDirModel(self)
dirs.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot)
completer.setModel(dirs)
completer.setCaseSensitivity(Qt.CaseInsensitive)
completer.setCompletionMode(QCompleter.PopupCompletion)
l = QLabel(
u"<b>Ingresá el directorio donde descargar los videos...</b>")
l.setTextFormat(Qt.RichText)
grid.addWidget(l, 0, 0, 1, 2)
grid.addWidget(QLabel(u"Descargar en:"), 1, 0, 2, 1)
prv = config.get('downloaddir', '')
self.downloaddir_entry = QLineEdit(prv)
self.downloaddir_entry.setCompleter(completer)
self.downloaddir_entry.setPlaceholderText(u'Ingresá un directorio')
grid.addWidget(self.downloaddir_entry, 1, 1, 2, 2)
self.downloaddir_buttn = QPushButton(u"Elegir un directorio")
self.downloaddir_buttn.clicked.connect(self._choose_dir)
grid.addWidget(self.downloaddir_buttn, 2, 1, 3, 2)
self.autoreload_checkbox = QCheckBox(
u"Recargar automáticamente la lista de episodios al iniciar")
prv = config.get('autorefresh', False)
self.autoreload_checkbox.setChecked(prv)
grid.addWidget(self.autoreload_checkbox, 3, 0, 4, 2)
self.shownotifs_checkbox = QCheckBox(
u"Mostrar una notificación cuando termina cada descarga")
prv = config.get('notification', True)
self.shownotifs_checkbox.setChecked(prv)
grid.addWidget(self.shownotifs_checkbox, 4, 0, 5, 2)
示例9: DirCompleter
class DirCompleter( QCompleter ):
""" Completer for directory names """
def __init__( self, parent = None,
completionMode = QCompleter.PopupCompletion,
showHidden = False ):
QCompleter.__init__( self, parent )
self.__model = QDirModel( self )
if showHidden:
filters = QDir.Filters(QDir.Drives | QDir.AllDirs | QDir.Hidden)
else:
filters = QDir.Filters(QDir.Drives | QDir.AllDirs)
self.__model.setFilter( filters )
self.setModel( self.__model )
self.setCompletionMode( completionMode )
if parent:
parent.setCompleter( self )
return
示例10: FileSystemBrowser
class FileSystemBrowser(QTreeView):
"""simple file system browser"""
def __init__(self):
QTreeView.__init__(self)
self.model = QDirModel()
self.setModel(self.model)
self.setSortingEnabled(True)
self.setAlternatingRowColors(True)
self.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.setContextMenuPolicy(Qt.CustomContextMenu)
self.setAutoExpandDelay(500)
i = self.model.index(os.getcwd())
self.scrollTo(i)
self.expand(i)
self.setCurrentIndex(i)
for i in range(self.model.columnCount()):
self.resizeColumnToContents(i)
self.connect(self, SIGNAL("doubleClicked(QModelIndex)"), self.itemAction)
self.connect(self, SIGNAL("customContextMenuRequested(QPoint)"), self.showContextMenu)
def itemAction(self, mi):
"""default action (on doubleclick) for item at model index mi"""
fi = self.model.fileInfo(mi)
if self.model.isDir(mi):
return
path = str(fi.absoluteFilePath())
if not SimuVis4.Globals.fileTypeActions.openFile(path):
self.openExternal(path)
def showContextMenu(self, pos):
"""show context menu for item at pos"""
mi = self.indexAt(pos)
fi = self.model.fileInfo(mi)
m = QMenu()
self.path = str(fi.absoluteFilePath())
if self.model.isDir(mi):
m.addAction(QCoreApplication.translate('DataBrowser', 'Refresh'),
lambda x=mi: self.model.refresh(x))
else:
for a in SimuVis4.Globals.fileTypeActions.getActions(self.path):
# this is weird, ... but it works
m.addAction(a[0], lambda x=a[1]: x(self.path))
m.addSeparator()
m.addAction(QCoreApplication.translate('DataBrowser', 'Open external'),
self.openExternal)
a = m.exec_(self.mapToGlobal(pos))
def openExternal(self, path=None):
if not path:
path = self.path
QDesktopServices.openUrl(QUrl.fromLocalFile(path))
示例11: FileController
class FileController(object):
def __init__(self, manager, opusDataPath, parentWidget, listen_to_menu = True):
self.addTree(opusDataPath, parentWidget)
self.currentColumn = None
self.currentIndex = None
self.classification = ""
self.manager = manager
if listen_to_menu:
QObject.connect(self.treeview,
SIGNAL("customContextMenuRequested(const QPoint &)"),
self.process_custom_menu)
def addTree(self, opusDataPath, parentWidget):
self.containerWidget = parentWidget
self.opusDataPath = opusDataPath
self.treeview = QTreeView()
filters = QStringList()
filters.append("*.*")
#filters.append("*.py")
#filters.append("*.shp")
#filters.append("*.tif")
self.model = QDirModel(filters, QDir.Files|QDir.AllDirs|QDir.NoDotAndDotDot, QDir.Name)
self.treeview.setModel(self.model)
if self.opusDataPath:
self.treeview.setRootIndex(self.model.index(self.opusDataPath))
self.treeview.setColumnWidth(0,200)
self.treeview.hideColumn(2)
self.treeview.hideColumn(3)
self.containerWidget.layout().addWidget(self.treeview)
# Hook up to the mousePressEvent and pressed
self.treeview.setContextMenuPolicy(Qt.CustomContextMenu)
def close(self):
self.treeview.hide()
self.containerWidget.layout().removeWidget(self.treeview)
return True
def process_custom_menu(self, position):
raise Exception('Method processCustomMenu is not implemented')
示例12: addTree
def addTree(self, opusDataPath, parentWidget):
self.containerWidget = parentWidget
self.opusDataPath = opusDataPath
self.treeview = QTreeView()
filters = QStringList()
filters.append("*.*")
#filters.append("*.py")
#filters.append("*.shp")
#filters.append("*.tif")
self.model = QDirModel(filters, QDir.Files|QDir.AllDirs|QDir.NoDotAndDotDot, QDir.Name)
self.treeview.setModel(self.model)
if self.opusDataPath:
self.treeview.setRootIndex(self.model.index(self.opusDataPath))
self.treeview.setColumnWidth(0,200)
self.treeview.hideColumn(2)
self.treeview.hideColumn(3)
self.containerWidget.layout().addWidget(self.treeview)
# Hook up to the mousePressEvent and pressed
self.treeview.setContextMenuPolicy(Qt.CustomContextMenu)
示例13: data
def data(self, index, role=Qt.DisplayRole):
"""
This is called when mouse-over of the dirmodel sections
"""
if index.isValid() and (index.column() == 0) and (role == Qt.CheckStateRole):
dir_now = unicode(self.filePath(index))
partial = self.__partial_check(dir_now)
if partial is not None:
return partial
elif dir_now in self.check_list['includes']:
return Qt.Checked
elif self.recursive is True:
par_dir = "/".join(unicode(dir_now).split("/")[:-1])
# the item is checked only if we have stored its path
if dir_now in self.check_list['excludes']:
return Qt.Unchecked
elif par_dir in self.check_list['excludes']:
return Qt.Unchecked
else:
# Recursively go down directory from parent to
# see if it should be included
checker = dir_now.split("/")
for val in range(1, len(checker)):
dir_part = "/".join(checker[:val+1])
if dir_part in self.check_list['includes']:
return Qt.Checked
# Nothing found
return Qt.Unchecked
else:
return Qt.Unchecked
# Standard QDirModel functionality
else:
return QDirModel.data(self, index, role)
示例14: EkdSaveDialog
class EkdSaveDialog(QDialog):
'''
EkdSaveDialog : Classe représentant la boite de dialogue utiliser lors de
l'enregistrement des modification sur un fichier donné
attributs : suffix - Suffix utilisé en filtre
filter - Filtre (déduit à partir du suffix)
chemin - Chemin du dernier fichier enregistré
multiple - va-t-on enregistrer plus d'un fichier ?
(ex: extraction d'image d'une vidéo)
méthodes : getFile - Invoque la boite de dialogue et retourne
le fichier saisi
'''
### Pourquoi avoir réimplémenté cette classe au lieu de passer par
### QFileDialog ?
## Correction du bug de consommation mémoire
##
## Explication du problème :
## Par défaut un QFileDialog utilise un QFileSystemModel qui lui
## crée un QWatchFileSystem
## Hors QWatchFileSystem scan régulièrement les changement
## dans le répertoire courant
## Ce phénomène provoque une réaction en chaine :
## 1 - je choisi mon répertoire de destination d'enregistrement
## de mes images
## 2 - ffmpeg se lance
## 3 - ffmpeg crée un fichier dans l'arborescence
## 4 - QWatchFileSystem (est toujours dans le répertoire courant)
## détecte un changement
## et recharge l'ensemble du contenue du répertoire
## 5 - goto 3 jusqu'à plus de mémoire ou fin du process ffmpeg
##
##
def __init__(self, parent, path = None, suffix = '', title = u"Sauver",
multiple = False, mode = None):
if type(suffix) == tuple or type(suffix) == list :
sfilter=""
for s in suffix :
sfilter += "*"+s+" "
self.filter=sfilter[:-1]
# Si on a plusieur suffix, on prend le premier par défaut pour
# la sauvegarde
self.suffix = suffix[0]
else :
self.suffix = suffix
self.filter = "*" + self.suffix
QDialog.__init__(self, parent)
self.setWindowTitle(title)
self.multiple = multiple
self.mode = mode
if not path:
if self.mode == "image" :
path = EkdConfig.get("general", "image_output_path")
elif self.mode == "video" :
path = EkdConfig.get("general", "video_output_path")
elif self.mode == "audio" :
path = EkdConfig.get("general", "sound_output_path")
else :
path = unicode(QDir.homePath())
# Nom du répertoire courant
self.location = QLabel("<b>%s</b>" % path)
# Variable permettant de savoir à tout moment le répertoire courant.
self.currentDir = path
self.mkdirButton = QPushButton(u" Créer un répertoire")
self.mkdirButton.setIcon(QIcon("Icones" + os.sep + "add_sub_task.png"))
if int(EkdConfig.get("general", "show_hidden_files")) :
#print "hidden shown"
EkdPrint(u"hidden shown")
shf = QDir.Hidden
else : shf = QDir.Readable
# Liste des fichiers
self.dirList = QListView()
sorting = QDir.DirsFirst
if int(EkdConfig.get("general", "ignore_case")):
sorting |= QDir.IgnoreCase
self.sorting = sorting
self.flags = QDir.Files | QDir.Readable | shf
self.dirModel = QStandardItemModel()
self.dirList.setModel(self.dirModel)
self.updateDir(path)
self.dirList.setWrapping(True)
#panneau latéral
self.dirTree = QTreeView()
self.dirModelLight = QDirModel(QStringList(""), QDir.AllDirs |
QDir.NoDotAndDotDot | shf, QDir.DirsFirst |
QDir.Name | QDir.IgnoreCase)
self.dirTree.setModel(self.dirModelLight)
self.dirTree.setColumnHidden(1,True)
self.dirTree.setColumnHidden(2,True)
self.dirTree.setColumnHidden(3,True)
self.dirTree.setMaximumWidth(200)
self.dirTree.setMinimumWidth(150)
self.dirTree.setCurrentIndex(self.dirModelLight.index(path))
self.dirTree.resizeColumnToContents(0)
#.........这里部分代码省略.........
示例15: setData
def setData(self, index, value, role = Qt.EditRole):
"""
Things to do on user made changes
"""
# user trying to do something to the checkbox
if index.isValid() and (index.column() == 0) and (role == Qt.CheckStateRole):
dir_now = unicode(self.filePath(index))
# store checked paths, remove unchecked paths
if value == Qt.Checked:
if self.recursive is False:
if dir_now not in self.check_list['includes']:
self.check_list['includes'].append(dir_now)
return True
tmp_list = []
for dir in self.check_list['includes']:
if dir_now in dir:
tmp_list.append(dir)
for dir in tmp_list:
self.check_list['includes'].remove(dir)
# No point adding if it's root dir is already there
checker = dir_now.split("/")
there = False
for val in range(len(checker)):
thing = "/".join(checker[:val+1])
if thing in self.check_list['includes']:
there = True
break
try:
tmp_list = []
for exc_dir in self.check_list['excludes']:
if dir_now in exc_dir:
tmp_list.append(exc_dir)
for thing in tmp_list:
self.check_list[1].remove(thing)
except ValueError:
# Doesn't exist yet
pass
if there is False:
self.check_list['includes'].append(unicode(self.filePath(index)))
self.needsRefresh.emit(index)
return True
# Want to exclude dir
else:
par_dir = "/".join(dir_now.split("/")[:-1])
tmp_list = (list(self.check_list['includes']),
list(self.check_list['excludes']))
for item in tmp_list[0]:
# removes if we've already checked it
if dir_now in item:
self.check_list['includes'].remove(item)
# Only add to unchecked if anything above is checked
checker = dir_now.split("/")
for val in range(len(checker)):
thing = "/".join(checker[:val+1])
if thing in self.check_list['includes']:
self.check_list['excludes'].append(dir_now)
self.needsRefresh.emit(index)
return True
# Standard QDirModel functionality
else:
return QDirModel.setData(self, index, value, role)