def add_file(self, filename): if filename not in self.filenames: # make filenames unicode-safe for Qt (#141) filename = filename.encode('utf-8').decode('utf-8', 'replace') self.filenames.append(filename) fileinfo = QtCore.QFileInfo(filename) basename = os.path.basename(filename.rstrip('/')) ip = QtGui.QFileIconProvider() icon = ip.icon(fileinfo) if os.path.isfile(filename): size = helpers.human_readable_filesize(fileinfo.size()) else: size = helpers.human_readable_filesize( helpers.dir_size(filename)) item_name = unicode('{0:s} ({1:s})'.format(basename, size)) item = QtGui.QListWidgetItem(item_name) item.setToolTip(QtCore.QString(size)) item.setIcon(icon) self.addItem(item) self.files_updated.emit()
class DockWidget(QtGui.QDockWidget, FORM_CLASS): """The DockWidget class for the Qlr Panel. """ iconProvider = QtGui.QFileIconProvider() closingPlugin = pyqtSignal() itemStateChanged = pyqtSignal(object, bool) def __init__(self, iface=None): """ Constructor. Sets the parent, sets up the UI and fills the tree. """ parent = None if iface is None else iface.mainWindow() super(DockWidget, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.config = QSettings() self.readconfig() self.setupUi(self) self.iface = iface
def handleDirectoryChangedSlot( self, _s_directory ): self.ui.directoryListWidget.clear() self.s_currentDirectory = os.path.normpath( os.path.abspath( str(_s_directory) ) ) self.ui.urlLineEdit.setText( self.s_currentDirectory ) o_qdir = QtCore.QDir( self.s_currentDirectory ) # Mise a jour liste des repertoires #--------------------------------------------------------------- o_qdir.setFilter( QtCore.QDir.Dirs ) t_dirList = o_qdir.entryList() if not t_dirList.isEmpty(): self.ui.directoryListWidget.setEnabled(True) self.ui.directoryListWidget.addItems( t_dirList ) o_qFileIconProvider = QtGui.QFileIconProvider() for o_item in self.iterAllDirectories(): o_item.setIcon( o_qFileIconProvider.icon( QtCore.QFileInfo(o_qdir, o_item.text()) ) ) else: self.ui.directoryListWidget.setEnabled(False) # Mise a jour de la liste de tous les fichiers (hors filtre) contenu # dans le repertoire courant #--------------------------------------------------------------- o_qdir.setFilter( QtCore.QDir.Files | QtCore.QDir.NoDotAndDotDot ) self.t_allFilesInCurrentDirectory = o_qdir.entryList() self.updateFileListWidget()
def qfileicon(self, path): """ desc: Gets an filetype icon for a file. arguments: path: The full path to the file. The file must exist. returns: type: QIcon """ return QtGui.QFileIconProvider().icon(QtCore.QFileInfo(path))
def updateFileListWidget( self ): self.ui.fileListWidget.clear() o_rx = QtCore.QRegExp( self.s_currentFilter ) o_rx.setPatternSyntax( QtCore.QRegExp.Wildcard ) # On filtre avec exactMatch (la fonction filter de QStringList n'applique pas un exact match) #t_filteredFileList = self.t_allFilesInCurrentDirectory.filter( o_rx ) t_filteredFileList = QtCore.QStringList( [ f for f in self.t_allFilesInCurrentDirectory if o_rx.exactMatch(f) ] ) if not t_filteredFileList.isEmpty(): self.ui.fileListWidget.setEnabled(True) self.ui.fileListWidget.addItems( t_filteredFileList ) o_qdir = QtCore.QDir( self.s_currentDirectory ) o_qFileIconProvider = QtGui.QFileIconProvider() for o_item in self.iterAllFiles(): o_item.setIcon( o_qFileIconProvider.icon( QtCore.QFileInfo(o_qdir, o_item.text()) ) ) else: self.ui.fileListWidget.setEnabled(False)
import os
class DockWidget(QtGui.QDockWidget, FORM_CLASS): """The DockWidget class for the Qlr Panel. """ iconProvider = QtGui.QFileIconProvider() closingPlugin = pyqtSignal() itemStateChanged = pyqtSignal(object, bool) refreshButtonClicked = pyqtSignal() def __init__(self, iface=None): """ Constructor. Sets the parent, sets up the UI and fills the tree. """ parent = None if iface is None else iface.mainWindow() super(DockWidget, self).__init__(parent) # Set up the user interface from Designer. # After setupUI you can access any designer object by doing # self.<objectname>, and you can use autoconnect slots - see # http://qt-project.org/doc/qt-4.8/designer-using-a-ui-file.html # #widgets-and-dialogs-with-auto-connect self.setupUi(self) self.iface = iface # UI self.filterLineEdit.setPlaceholderText(self.trUtf8(u'Filter')) self.treeWidget.setColumnCount(1) self.treeWidget.header().hide() # Properties self.root_paths = set() self.file_system = {} self.checked_paths = set() # Signals self.treeWidget.itemDoubleClicked.connect(self._treeitem_doubleclicked) self.treeWidget.itemChanged.connect(self._treeitem_changed) self.refreshButton.clicked.connect(self.refreshClicked) # Search self.timer = QTimer(self) self.timer.setSingleShot(True) self.timer.setInterval(500) self.timer.timeout.connect(self._fillTree) #self.filterLineEdit.textChanged.connect(self._fillTree) self.filterLineEdit.textChanged.connect(self.timer.start) # Default fill self._fillTree() def addRootPath(self, path): """Adds the root path and sets up the File System Model and connects it to the _fillTree method. """ if os.path.exists(path): self.root_paths.add(path) fs = FileSystemModel() self.file_system[path] = fs fs.updated.connect(self._fillTree) try: fs.setRootPath(path) except FileSystemRecursionException as e: message = self.trUtf8( "Configured base path has too many files (> {})").format( e.maxcount) self._setRootPathMessage(message) def removeRootPath(self, path): """ Removes the Root Path and disconnects the fillTree() method. """ self.root_paths.remove(path) fs = self.file_system.pop(path, None) fs.updated.disconnect(self._fillTree) def setPathCheckState(self, path, newState): """Sets the check state of a path. """ oldState = path in self.checked_paths if newState: self.checked_paths.add(path) elif path in self.checked_paths: self.checked_paths.remove(path) self._updateTree(path) def getIsPathChecked(self, path): """ Returns true whth the path is checked. :param path: string """ return path in self.checked_paths def getNumCheckedSubPaths(self, path): """ Returns the number of checked items in all subpaths of this element :param path: string :return: integer, number of checked paths """ count = sum((1 for x in self.checked_paths if self.is_child_directory(x, path))) return count def reloadFileSystemInfo(self): """Updates the file system info for each element. """ for fs in self.file_system.values(): try: fs.update() except FileSystemRecursionException as e: self._setRootPathMessage( self.trUtf8( "Configured base path has too many files (> {})". format(self.config.get('max_file_system_objects', 1000)))) def refreshClicked(self): self.reloadFileSystemInfo() self.refreshButtonClicked.emit() @pyqtSlot(QtGui.QTreeWidgetItem, int) def _treeitem_doubleclicked(self, item, column): """ Triggered on a doubleclick event of a Tree Widget. """ if item.fileitem.isdir: return newState = Qt.Checked if item.checkState( column) == Qt.Unchecked else Qt.Unchecked item.setCheckState(column, newState) @pyqtSlot(QtGui.QTreeWidgetItem, int) def _treeitem_changed(self, item, column): """ Triggered on a change event of a Tree Widget. """ checked = item.checkState(column) == Qt.Checked path = item.fullpath if checked: # Dont try to turn on a non-existing qlr if not self._checkFileItemExists(path): # Path no longer exists. Reload filesystem self.reloadFileSystemInfo() return self.setPathCheckState(path, checked) self.itemStateChanged.emit(item.fileitem, checked) def _updateTree(self, filter_path=None): """ Updates tree display :filter_path , string, Optionally only the branch which includes filter_path """ iterator = QtGui.QTreeWidgetItemIterator(self.treeWidget) item = iterator.value() while item: # Skip if we only need to update part of tree if not filter_path or filter_path.startswith(item.fullpath): # checked sub paths if item.fileitem.isdir: num = self.getNumCheckedSubPaths(item.fullpath) item.setSubChecked(num) # checked checked = self.getIsPathChecked(item.fullpath) item.setCheckState(0, Qt.Unchecked if not checked else Qt.Checked) iterator += 1 item = iterator.value() def _fillTree(self): """ Fills the tree with items. """ if len(self.root_paths) < 1: self._setRootPathMessage( self.trUtf8("No base directory configured...")) return self.treeWidget.clear() for basepath in self.root_paths: fileitem = self._filteredFileItems(basepath) if fileitem: baseTreeItem = self._createWidgetItem(fileitem) self._fillTreeRecursively(baseTreeItem, fileitem) self.treeWidget.addTopLevelItem(baseTreeItem) baseTreeItem.setExpanded(True) if self.filterLineEdit.text().strip(): self._expandTree() def _expandTree(self): """ Expands the tree. """ iterator = QtGui.QTreeWidgetItemIterator(self.treeWidget) item = iterator.value() while item: if item.fileitem.matches(self.filterLineEdit.text().strip()): tmpitem = item while tmpitem: tmpitem.setExpanded(True) tmpitem = tmpitem.parent() else: item.setExpanded(False) iterator += 1 item = iterator.value() def _filteredFileItems(self, basepath): """ Returns the filtered items of the basepath. :basepath: string """ # For now just return unfiltered fs = self.file_system[basepath] filterText = self.filterLineEdit.text().strip() if filterText: return fs.rootitem.filtered(filterText) else: return fs.rootitem def _fillTreeRecursively(self, baseWidgetItem, baseFileItem): """ Fills a baseWidgetItem into the baseFileItem """ if not baseFileItem.isdir: return for child in baseFileItem.children: childTreeItem = self._createWidgetItem(child) if child.isdir: self._fillTreeRecursively(childTreeItem, child) baseWidgetItem.addChild(childTreeItem) def _createWidgetItem(self, fileitem): """ Creates a widget item from a file item. """ checked = self.getIsPathChecked(fileitem.fullpath) num_checked_sub_paths = 0 if fileitem.isdir: num_checked_sub_paths = self.getNumCheckedSubPaths( fileitem.fullpath) return TreeWidgetItem(fileitem, checked, num_checked_sub_paths) def _checkFileItemExists(self, path): """ Returns true if a path exists. :path string :returns boolean """ if os.path.exists(path): return True else: self.iface.messageBar().pushMessage( self.trUtf8("Qlr Browser Error"), self.trUtf8("The selected path does not exist anymore"), level=QgsMessageBar.CRITICAL) return False def _setRootPathMessage(self, message): self.treeWidget.clear() baseTreeItem = QtGui.QTreeWidgetItem([message]) font = baseTreeItem.font(0) font.setItalic(True) baseTreeItem.setFont(0, font) self.treeWidget.addTopLevelItem(baseTreeItem) # # Events # def closeEvent(self, event): self.closingPlugin.emit() event.accept() def is_child_directory(self, child_dir, parent_dir): """ Returns true if child_dir is inside parent_dir. :param child_dir :param parent_dir :return: boolean """ parent_dir = os.path.join(os.path.realpath(parent_dir), '') child_dir = os.path.realpath(child_dir) return os.path.commonprefix([child_dir, parent_dir]) == parent_dir
def iconFromPath(path): fileInfo = QtCore.QFileInfo(path) iconProvider = QtGui.QFileIconProvider() icon = iconProvider.icon(fileInfo) return icon
def icon(self): provider = QtGui.QFileIconProvider() return provider.icon(QtGui.QFileIconProvider.Drive)
def icon(self): provider = QtGui.QFileIconProvider() if self.prefix == "url-datasets": return provider.icon(QtGui.QFileIconProvider.Network) return provider.icon(QtGui.QFileIconProvider.Drive)