def __init__(self, parent): super().__init__(parent=parent) self._folder = None self._filter = "*" self._children = [] self._iconProvider = QFileIconProvider() self._reset(self._folder, self._filter)
def _load(filePath): # type: (pathlib.Path) -> NoReturn with itemsLock: icon = self.__iconsCache.get(filePath) if icon is None: iconProvider = QFileIconProvider() posixPath = filePath.as_posix() file = QFileInfo(posixPath) icon = iconProvider.icon(file) if icon.isNull(): mimeDb = QMimeDatabase() for mime in mimeDb.mimeTypesForFileName(posixPath): icon = QIcon.fromTheme(mime.iconName()) if not icon.isNull(): break result = QFileIconLoader.LoadResult(filePath, icon) with itemsLock: loadedItems[filePath] = result self.__iconsCache.set(filePath, icon) self.loaded.emit(result) if len(loadedItems) == len(targetPaths): self.completed.emit(loadedItems)
def populate_template_model(self, populate): """Add all tool template specs to a single QTreeView. If items is None or an empty list, model is cleared. Args: populate (bool): False to clear model, True to populate. """ self.template_model.clear() self.template_model.setHorizontalHeaderItem( 0, QStandardItem("Template specification")) # Add header # Add category items source_file_category_item = QStandardItem("Source files") input_category_item = QStandardItem("Input files") opt_input_category_item = QStandardItem("Optional input files") output_category_item = QStandardItem("Output files") self.template_model.appendRow(source_file_category_item) self.template_model.appendRow(input_category_item) self.template_model.appendRow(opt_input_category_item) self.template_model.appendRow(output_category_item) if populate: if self.source_file_model.rowCount() > 0: for row in range(self.source_file_model.rowCount()): text = self.source_file_model.item(row).data( Qt.DisplayRole) qitem = QStandardItem(text) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(text)), Qt.DecorationRole) source_file_category_item.appendRow(qitem) if self.input_file_model.rowCount() > 0: for row in range(self.input_file_model.rowCount()): text = self.input_file_model.item(row).data(Qt.DisplayRole) qitem = QStandardItem(text) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(text)), Qt.DecorationRole) input_category_item.appendRow(qitem) if self.opt_input_file_model.rowCount() > 0: for row in range(self.opt_input_file_model.rowCount()): text = self.opt_input_file_model.item(row).data( Qt.DisplayRole) qitem = QStandardItem(text) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(text)), Qt.DecorationRole) opt_input_category_item.appendRow(qitem) if self.output_file_model.rowCount() > 0: for row in range(self.output_file_model.rowCount()): text = self.output_file_model.item(row).data( Qt.DisplayRole) qitem = QStandardItem(text) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(text)), Qt.DecorationRole) output_category_item.appendRow(qitem)
def __init__(self): QWidget.__init__(self) mainWidget = QWidget() mainWidget.setFixedSize(400,300) mainWidget.setWindowTitle('IHM') mainWidget.setWindowIcon(self.icon) self.icon = QFileIconProvider('https://drive.google.com/file/d/1rRc9g8vKTRm5GZGAh68T0Izv2kwM2A7l/view') self.layout = QVBoxLayout() self.label = QLabel('Hello World') self.label.setAlignment(Qt.AlignCenter) self.bar = QProgressBar() self.bar.setValue(50) self.linedit = QLineEdit self.button = QPushButton() self.button.setToolTip('Welcome !') self.layout.addWidget(self.icon) self.layout.addWidget(self.label) self.layout.addWidget(self.bar) self.layout.addWidget(self.linedit) self.layout.addWidget(self.button) self.setLayout(self.layout)
def __init__(self): QWidget.__init__(self) mainWidget = QWidget() mainWidget.setFixedSize(400, 300) self.setWindowTitle("IHM") mainWidget.setWindowIcon(self.icon) self.icon = QFileIconProvider( 'https://drive.google.com/file/d/1rRc9g8vKTRm5GZGAh68T0Izv2kwM2A7l/view' ) self.layout = QVBoxLayout() self.label = QLabel("Label") self.layout.setAlignement(self.label) self.ProgressBar = QProgressBar() self.ProgressBar.setvalue(3) self.LineEdit = QLineEdit() self.button = QPushButton() self.button.setToolPip("Hello") self.layout.addwidget(self.icon) self.layout.addwidget(self.label) self.layout.addwidget(self.bar) self.layout.addwidget(self.LineEdit) self.layout.addwidget(self.button) self.setLayout(self.layout)
def add_single_include(self, path): """Add file path to Source files list.""" dirname, file_pattern = os.path.split(path) # logging.debug("program path:{0}".format(self.program_path)) # logging.debug("{0}, {1}".format(dirname, file_pattern)) if not self.program_path: self.program_path = dirname self.ui.label_mainpath.setText(self.program_path) path_to_add = file_pattern else: # check if path is a descendant of main dir. common_prefix = os.path.commonprefix([os.path.abspath(self.program_path), os.path.abspath(path)]) # logging.debug("common_prefix:{0}".format(common_prefix)) if common_prefix != self.program_path: self.statusbar.showMessage( "Source file {0}'s location is invalid " "(should be in main directory)".format(file_pattern), 5000 ) return False path_to_add = os.path.relpath(path, self.program_path) if self.sourcefiles_model.findItems(path_to_add): self.statusbar.showMessage("Source file {0} already included".format(path_to_add), 5000) return False qitem = QStandardItem(path_to_add) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(path_to_add)), Qt.DecorationRole) self.sourcefiles_model.appendRow(qitem) return True
def setupModelData(self, parent): parents = [parent] numAssets = rt.AssetManager.getNumAssets() # For each asset (row) for i in range(1, numAssets + 1): # Get the asset object asset = rt.AssetManager.getAssetByIndex(i) # Get the asset properties assetFilename = asset.GetFilename() assetBasename = os.path.basename(assetFilename) assetName = os.path.splitext(assetBasename)[0] assetPath = os.path.dirname(assetFilename) assetExt = os.path.splitext(assetBasename)[1] if assetExt == "": continue assetType = str(asset.GetType()) assetStatus = os.path.exists(assetFilename) if (assetStatus): assetSize = os.path.getsize(assetFilename) else: assetSize = 0 # We'll use QFileIconProvider to grab the icon that the OS # is currently using to grab the icon to display in the view fileInfo = QtCore.QFileInfo(assetFilename) iconProvider = QFileIconProvider() assetIcon = iconProvider.icon(fileInfo) # Read the column data from the rest of the line. columnData = [ assetName, assetExt, assetPath, assetType, os.path.exists(assetFilename), assetSize ] # Append a new node to the root parent = parents[-1] parent.insertChildren(parent.childCount(), 1, self._rootItem.columnCount()) node = parent.child(parent.childCount() - 1) # Fill each column in the current row for column in range(len(columnData)): node.setData(column, columnData[column]) node.setIcon(assetIcon)
def populate_output_file_model(self, items): """Add Tool output files into a model. If items is None or an empty list, model is cleared.""" self.output_file_model.clear() if items is not None: for item in items: qitem = QStandardItem(item) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) self.output_file_model.appendRow(qitem)
def populate_outputfiles_list(self, items): """List output files in QTreeView. If items is None or empty list, model is cleared. """ self.outputfiles_model.clear() self.outputfiles_model.setHorizontalHeaderItem(0, QStandardItem("Output files")) # Add header if items is not None: for item in items: qitem = QStandardItem(item) qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) self.outputfiles_model.appendRow(qitem)
def populate_sourcefile_list(self, items): """List source files in QTreeView. If items is None or empty list, model is cleared. """ self.sourcefiles_model.clear() self.sourcefiles_model.setHorizontalHeaderItem(0, QStandardItem("Additional source files")) # Add header if items is not None: for item in items: qitem = QStandardItem(item) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) self.sourcefiles_model.appendRow(qitem)
def populate_source_file_model(self, items): """Add required source files (includes) into a model. If items is None or an empty list, model is cleared.""" self.source_file_model.clear() # self.source_file_model.setHorizontalHeaderItem(0, QStandardItem("Source files")) # Add header if items is not None: for item in items: qitem = QStandardItem(item) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) self.source_file_model.appendRow(qitem)
def populate_opt_input_file_model(self, items): """Add optional Tool template files into a model. If items is None or an empty list, model is cleared.""" self.opt_input_file_model.clear() # self.opt_input_file_model.setHorizontalHeaderItem(0, QStandardItem("Optional input files")) # Add header if items is not None: for item in items: qitem = QStandardItem(item) qitem.setFlags(~Qt.ItemIsEditable) qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) self.opt_input_file_model.appendRow(qitem)
def _set_icon_label(self, icon_info, icon_label): image, mime, file_info = icon_info pixmap = None if image: pixmap = QPixmap(self.FILE_LIST_ICON_SIZE, self.FILE_LIST_ICON_SIZE) pixmap.convertFromImage(image) elif mime: icon = self._get_icon(mime) if icon: pixmap = icon.pixmap( self.FILE_LIST_ICON_SIZE, self.FILE_LIST_ICON_SIZE) if not pixmap or pixmap.isNull(): icon = QFileIconProvider().icon(file_info) pixmap = icon.pixmap( self.FILE_LIST_ICON_SIZE, self.FILE_LIST_ICON_SIZE) if pixmap and not pixmap.isNull(): icon_label.setPixmap(pixmap) icon_label.setScaledContents(True) icon_label.setFixedSize( self.FILE_LIST_ICON_SIZE, self.FILE_LIST_ICON_SIZE) icon_label.setAlignment(Qt.AlignCenter)
def set_texture(self, filename): # load image p = Path(filename) suffix = p.suffix[1:].upper() try: if p.is_file() and suffix in self._supported_images: pim = Image.open(filename) img = ImageQt(pim) self.info = f"{pim.format} - {pim.size} - {pim.mode} " else: ico = QFileIconProvider().icon(QFileInfo(filename)) pix = ico.pixmap(256, 256) img = pix.toImage() self.info = "not an image " except UnidentifiedImageError as e: print("UnidentifiedImageError:\n", e, flush=True) return self._texture_size = img.width(), img.height() self.__update_scale(self.width(), self.height()) # create texture self.makeCurrent() self._texture = QOpenGLTexture(QOpenGLTexture.Target2D) self._texture.create() self._texture.bind() self._texture.setMinMagFilters(QOpenGLTexture.LinearMipMapLinear, QOpenGLTexture.Linear) self._texture.setWrapMode(QOpenGLTexture.DirectionS, QOpenGLTexture.Repeat) self._texture.setWrapMode(QOpenGLTexture.DirectionT, QOpenGLTexture.Repeat) self._texture.setData(img) self._texture.release() # redraw self.update()
def __init__(self, name: str, itemType: FileSystemItemType, parent: QObject = None): if itemType == FileSystemItemType.Drive: iconType = QFileIconProvider.IconType.Drive elif itemType == FileSystemItemType.Directory: iconType = QFileIconProvider.IconType.Folder else: iconType = QFileIconProvider.IconType.File icon = FileSystemItem._iconCache.get(iconType, None) if icon is None: icon = QFileIconProvider().icon(iconType) FileSystemItem._iconCache[iconType] = icon super().__init__(icon, name, parent) self.itemType = itemType
def add_inputfiles(self, checked=False): """Let user select input files for this tool template.""" msg = "Add an input file or a directory required by your program. Wildcards " \ "<b> are not</b> supported.<br/><br/>" \ "Examples:<br/>" \ "<b>data.csv</b> -> File is copied to the same work directory as the main program.<br/>" \ "<b>input/data.csv</b> -> Creates subdirectory input\ to the work directory and " \ "copies the file there.<br/>" \ "<b>output/</b> -> Creates an empty directory into the work directory.<br/><br/>" # noinspection PyCallByClass, PyTypeChecker, PyArgumentList answer = QInputDialog.getText(self, "Add input item", msg, flags=Qt.WindowTitleHint | Qt.WindowCloseButtonHint) file_name = answer[0] if not file_name: # Cancel button clicked return qitem = QStandardItem(file_name) qitem.setData(QFileIconProvider().icon(QFileInfo(file_name)), Qt.DecorationRole) self.inputfiles_model.appendRow(qitem)
def add_outputfiles(self, checked=False): """Let user select output files for this tool template.""" msg = "Add output files that will be archived into the Tool results directory after the <br/>" \ "Tool template has finished execution. Wildcards are supported.<br/><br/>" \ "Examples:<br/>" \ "<b>results.csv</b> -> File is copied from work directory into results.<br/> " \ "<b>*.csv</b> -> All CSV files will copied into results.<br/> " \ "<b>output\*.gdx</b> -> All GDX files from the work output\ directory will be copied into <br/>" \ "output\ subdirectory in the results directory.<br/><br/>" # noinspection PyCallByClass, PyTypeChecker, PyArgumentList answer = QInputDialog.getText(self, "Add output item", msg, flags=Qt.WindowTitleHint | Qt.WindowCloseButtonHint) file_name = answer[0] if not file_name: # Cancel button clicked return qitem = QStandardItem(file_name) qitem.setData(QFileIconProvider().icon(QFileInfo(file_name)), Qt.DecorationRole) self.outputfiles_model.appendRow(qitem)
def add_inputfiles_opt(self, checked=False): """Let user select optional input files for this tool template.""" msg = "Add optional input files that may be utilized by your program. <br/>" \ "Wildcards are supported.<br/><br/>" \ "Examples:<br/>" \ "<b>data.csv</b> -> If found, file is copied to the same work directory as the main program.<br/>" \ "<b>*.csv</b> -> All found CSV files are copied to the same work directory as the main program.<br/>" \ "<b>input/data_?.dat</b> -> All found files matching the pattern 'data_?.dat' will be copied to <br/>" \ "input/ subdirectory under the same work directory as the main program.<br/><br/>" # noinspection PyCallByClass, PyTypeChecker, PyArgumentList answer = QInputDialog.getText(self, "Add optional input item", msg, flags=Qt.WindowTitleHint | Qt.WindowCloseButtonHint) file_name = answer[0] if not file_name: # Cancel button clicked return qitem = QStandardItem(file_name) qitem.setData(QFileIconProvider().icon(QFileInfo(file_name)), Qt.DecorationRole) self.inputfiles_opt_model.appendRow(qitem)
def populate_data_list(self, items): """List project internal data (files) in QTreeView. If items is None or empty list, model is cleared. """ self.data_model.clear() self.data_model.setHorizontalHeaderItem( 0, QStandardItem("Data")) # Add header if items is not None: for item in items: qitem = QStandardItem(item) qitem.setFlags(~Qt.ItemIsEditable) if item == 'datapackage.json': qitem.setData(self.datapackage_icon, Qt.DecorationRole) else: qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) full_path = os.path.join(self.data_dir, item) # For drag and drop qitem.setData(full_path, Qt.UserRole) self.data_model.appendRow(qitem)
def update_file_model(self, items): """Adds given list of items to the file model. If None or an empty list is given, the model is cleared. Args: items (set): Set of absolute file paths """ self.all_files = items self.file_model.clear() self.file_model.setHorizontalHeaderItem(0, QStandardItem("Source files")) # Add header if items is not None: for item in items: qitem = QStandardItem(item) qitem.setEditable(False) qitem.setCheckable(True) if item in self.unchecked_files: qitem.setCheckState(Qt.Unchecked) else: qitem.setCheckState(Qt.Checked) qitem.setData(QFileIconProvider().icon(QFileInfo(item)), Qt.DecorationRole) self.file_model.appendRow(qitem)
def data(self, index, role=Qt.DisplayRole): """Returns data associated with given role at given index.""" if not index.isValid(): return None if role == Qt.DisplayRole: return self._files[index.row()].label if role == Qt.CheckStateRole: return Qt.Checked if self._files[index.row()].selected else Qt.Unchecked if role == Qt.DecorationRole: path = self._files[index.row()].path if path: return QFileIconProvider().icon(QFileInfo(path)) if role == Qt.ToolTipRole: item = self._files[index.row()] if not item.exists(): if item.is_pattern: tooltip = f"These files will be generated by {item.provider_name} upon execution." else: tooltip = f"This file will be generated by {item.provider_name} upon execution." else: tooltip = item.path return tooltip return None
class SD_FS_Model(QAbstractItemModel): def __init__(self, parent=None, *args): super().__init__(parent, *args) self.root = FS_Item("/") self.header_labels = ['Name', 'Children'] self.icon_provider = QFileIconProvider() # return an index for the given row/column pair and the parent element # this index is then used by views to access data def index(self, row: int, column: int, parent: QModelIndex = None) -> QModelIndex: if not parent or not parent.isValid(): parent_item = self.root else: parent_item = parent.internalPointer() # check if row is valid if row >= parent_item.child_count(): return QModelIndex() child_item = parent_item.child(row) # check if column is valid for child if column >= child_item.column_count(): return QModelIndex() # return the valid index for the childs column return self.createIndex(row, column, child_item) def parent(self, index: QModelIndex = None) -> QModelIndex: if not index.isValid(): return QModelIndex() child_item = index.internalPointer() parent_item = child_item.parent() # return invalid index if we hit root if parent_item == self.root: return QModelIndex() return self.createIndex(parent_item.row(), 0, parent_item) # returns the amount of nested rows aka children for the parent item the index identifies def rowCount(self, parent: QModelIndex = None) -> int: # if the column count is nonzero we return # indices that identify a node/row and not a value/field have column=0 by convention if parent is not None and parent.column() > 0: return 0 if not parent or not parent.isValid(): parent_item = self.root else: parent_item = parent.internalPointer() return parent_item.child_count() # returns the number of columns available for an index def columnCount(self, index: QModelIndex = None) -> int: # for now, we accept indices with column>0, as there is no drawback if index is not None and index.isValid(): return index.internalPointer().column_count() return self.root.column_count() # returns the value of the data attribute mapped to the column # column mapping is done in the respective class the CanItem holds # via the column_representation classmethod def data(self, index: QModelIndex, role: int = None): # we return None for root data or roles we dont serve if not index.isValid(): return None if role == Qt.DecorationRole and index.column() == 0: if index.internalPointer().dir: return self.icon_provider.icon(QFileIconProvider.Folder) else: return self.icon_provider.icon(QFileIconProvider.File) elif role == Qt.DisplayRole: # we get the desired data by calling the CanItems data() function # that then calls the held objects get_data function return index.internalPointer().data(index.column()) return None def flags(self, index: QModelIndex) -> Qt.ItemFlags: if not index.isValid(): return Qt.NoItemFlags return Qt.ItemIsEnabled | Qt.ItemIsSelectable # returns header labeling, atm just copied from the table model def headerData(self, section, orientation, role: Qt.DisplayRole = None): if role == Qt.DisplayRole and orientation == Qt.Orientation.Horizontal: return self.header_labels[section] return QAbstractTableModel.headerData(self, section, orientation, role) def add_item(self, index: QModelIndex, name: str, is_dir: bool): # find the parent if index is None or not index.isValid(): parent_item = self.root else: parent_item = index.internalPointer() item = FS_Item(name, is_dir=is_dir, parent=parent_item) # send insert signals and append child if index is not None: self.beginInsertRows(index, parent_item.child_count(), parent_item.child_count()) parent_item.append_child(item) self.endInsertRows() else: print(f"heres the bug: \n {item.name} \n {item.get_filepath()}") def remove_item(self, index: QModelIndex): # cant remove root if index is None or not index.isValid(): return # retrieve parameters fo signal call parent_item = index.internalPointer().parent() parent_index = self.parent(index) row = index.row() # remove child from parent self.beginRemoveRows(parent_index, row, row) parent_item.remove_child(row) self.endRemoveRows() def child_index_by_name(self, parent_index: QModelIndex, name: str) -> QModelIndex: if not parent_index.isValid(): parent = self.root else: parent = parent_index.internalPointer() for child in parent.children: if child.name == name: return self.createIndex(child.row(), 0, child) # no child has the name -> return invalid Index return QModelIndex() # search through the items according to the given directory path and return index to end of path def index_for_path(self, path: str) -> QModelIndex: # return an invalid index for the root if path == "/": return QModelIndex() slash1 = 0 slash2 = path.find("/", slash1 + 1) if slash2 == -1: directory = path[slash1 + 1:] else: directory = path[slash1 + 1:slash2] path_end_index = self.child_index_by_name(QModelIndex(), directory) while True: if not path_end_index.isValid(): # subdirectory not found, return None return None # go deeper if we have a longer path if slash2 != -1: slash1 = slash2 slash2 = path.find("/", slash1 + 1) else: return path_end_index if slash2 == -1: directory = path[slash1 + 1:] else: directory = path[slash1 + 1:slash2] path_end_index = self.child_index_by_name(path_end_index, directory) def is_filled(self) -> bool: return self.root.child_count() > 0
class FolderListModel(QAbstractTableModel): """ This class provides a model for browsing a folder. """ folderChanged = Signal(str) # emitted when the folder changes def __init__(self, parent): super().__init__(parent=parent) self._folder = None self._filter = "*" self._children = [] self._iconProvider = QFileIconProvider() self._reset(self._folder, self._filter) def setFolder(self, folder): """ set the folder of this browser :param folder: a Path or string instance :return: """ if Path(folder) != self._folder: self._reset(folder, self._filter) def setFilter(self, flt): """ Set the filter of this browser :param flt: string or a list of strings containing glob-style patterns :return: """ if isinstance(flt, str): flt = [flt] self._reset(self._folder, flt) def fileToIndex(self, filename): """ return the given file name to a model index. :param filename: a string or Path instance :return: a QModelIndex instance """ filename = Path(filename) try: idx = self._children.index(filename) return self.createIndex(idx, 0) except ValueError: return QModelIndex() def _match(self, path): if path.is_dir(): return True res = QDir.match(self._filter, path.name) return res def _reset(self, folder, flt): self.beginRemoveRows(QModelIndex(), 0, self.rowCount() - 1) self._folder = None self.endRemoveRows() if folder is not None: listDrives = False f = Path(folder).resolve() if platform.system() == "Windows": folder = Path(folder) if folder.name == ".." and folder.parent == Path(folder.drive + "/"): listDrives = True f = Path("<Drives>") self._folder = f self._filter = flt if platform.system() == "Windows": if listDrives: self._children = [ Path("%s:/" % dl) for dl in string.ascii_uppercase if Path("%s:/" % dl).exists() ] else: self._children = [f / ".."] else: self._children = ([] if f.root == f else [f / ".."]) if not listDrives: self._children += [x for x in f.glob("*") if self._match(x)] self._children.sort(key=lambda c: (c.is_file( ), c.drive, int(c.name != ".."), c.name)) self.beginInsertRows(QModelIndex(), 0, len(self._children) - 1) self.endInsertRows() if listDrives: self.folderChanged.emit("<Drives>") else: self.folderChanged.emit( str(self._folder) + (os.path.sep if self._folder.is_dir() else "")) def folder(self): """ Return the current folder. :return: a Path instance """ return self._folder def filter(self): """ Return the current filter :return: a list of strings """ return self._filter def columnCount(self, index=QModelIndex()): # pylint: disable=unused-argument """ overwritten from base class :param index: :return: """ return 4 def rowCount(self, index=QModelIndex()): # pylint: disable=unused-argument """ overwritten from base class :param index: :return: """ return len(self._children) def data(self, index, role): """ overwritten from base class :param index: :param role: :return: """ c = self._children[index.row()] if role == Qt.DisplayRole: if index.column() == 0: return c.name if c.name != "" else str(c) if index.column() == 1: if c.is_dir(): return "" try: s = c.stat().st_size except Exception: # pylint: disable=broad-except return "" if s >= 1024 * 1024 * 1024: return "%.0f GB" % (s / (1024 * 1024 * 1024)) if s >= 1024 * 1024: return "%.0f MB" % (s / (1024 * 1024)) if s >= 1024: return "%.0f kB" % (s / 1024) return s if index.column() == 2: try: return QDateTime.fromMSecsSinceEpoch(c.stat().st_mtime * 1000) except Exception: # pylint: disable=broad-except return "" if role == Qt.DecorationRole: if index.column() == 0: if c.is_dir(): return self._iconProvider.icon(QFileIconProvider.Drive) return self._iconProvider.icon(QFileInfo(str(c.absolute()))) if role == Qt.UserRole: if index.column() == 0: return c if role in [Qt.DisplayRole, Qt.EditRole]: if index.column() == 3: if index.row() > 0: return str(c) + (os.path.sep if c.is_dir() else "") return str(c.parent) + os.path.sep return None def headerData(self, section, orientation, role): """ overwritten from base class :param section: :param orientation: :param role: :return: """ if orientation == Qt.Horizontal and role == Qt.DisplayRole: return ["Name", "Size", "Time", ""][section] return super().headerData(section, orientation, role)
def addIconToTab(self, tab: LiveTab): index = self.indexOf(tab) icon = QFileIconProvider().icon(QFileIconProvider.IconType.Drive) self.setTabIcon(index, icon)
def __init__(self, parent=None, *args): super().__init__(parent, *args) self.root = FS_Item("/") self.header_labels = ['Name', 'Children'] self.icon_provider = QFileIconProvider()
def FileIcon(file_): return QFileIconProvider().icon(QFileInfo(file_))
def _make_icon(file_path): icon = '' if not file_path.endswith('.lnk'): icon = QFileIconProvider().icon(QFileInfo(file_path)).pixmap(50, 50) return icon
def __init__(self, parent): super().__init__(parent) iconProvider = QFileIconProvider() self.__defaultIcon = iconProvider.icon(QFileIconProvider.Folder) self.__driveIcon = iconProvider.icon(QFileIconProvider.Drive)