class FilenamePrompt(_BasePrompt): """A prompt for a filename.""" def __init__(self, question, parent=None): super().__init__(question, parent) self._init_texts(question) self._init_fileview() self._set_fileview_root(question.default) self._lineedit = LineEdit(self) if question.default: self._lineedit.setText(question.default) self._lineedit.textEdited.connect(self._set_fileview_root) self._vbox.addWidget(self._lineedit) self.setFocusProxy(self._lineedit) self._init_key_label() if config.get('ui', 'prompt-filebrowser'): self.setSizePolicy(QSizePolicy.Expanding, QSizePolicy.Preferred) @pyqtSlot(str) def _set_fileview_root(self, path, *, tabbed=False): """Set the root path for the file display.""" separators = os.sep if os.altsep is not None: separators += os.altsep dirname = os.path.dirname(path) try: if not path: pass elif path in separators and os.path.isdir(path): # Input "/" -> don't strip anything pass elif path[-1] in separators and os.path.isdir(path): # Input like /foo/bar/ -> show /foo/bar/ contents path = path.rstrip(separators) elif os.path.isdir(dirname) and not tabbed: # Input like /foo/ba -> show /foo contents path = dirname else: return except OSError: log.prompt.exception("Failed to get directory information") return root = self._file_model.setRootPath(path) self._file_view.setRootIndex(root) @pyqtSlot(QModelIndex) def _insert_path(self, index, *, clicked=True): """Handle an element selection. Args: index: The QModelIndex of the selected element. clicked: Whether the element was clicked. """ path = os.path.normpath(self._file_model.filePath(index)) if clicked: path += os.sep else: # On Windows, when we have C:\foo and tab over .., we get C:\ path = path.rstrip(os.sep) log.prompt.debug('Inserting path {}'.format(path)) self._lineedit.setText(path) self._lineedit.setFocus() self._set_fileview_root(path, tabbed=True) if clicked: # Avoid having a ..-subtree highlighted self._file_view.setCurrentIndex(QModelIndex()) def _init_fileview(self): self._file_view = QTreeView(self) self._file_model = QFileSystemModel(self) self._file_view.setModel(self._file_model) self._file_view.clicked.connect(self._insert_path) if config.get('ui', 'prompt-filebrowser'): self._vbox.addWidget(self._file_view) else: self._file_view.hide() # Only show name self._file_view.setHeaderHidden(True) for col in range(1, 4): self._file_view.setColumnHidden(col, True) # Nothing selected initially self._file_view.setCurrentIndex(QModelIndex()) # The model needs to be sorted so we get the correct first/last index self._file_model.directoryLoaded.connect( lambda: self._file_model.sort(0)) def accept(self, value=None): text = value if value is not None else self._lineedit.text() text = downloads.transform_path(text) if text is None: message.error("Invalid filename") return False self.question.answer = text return True def item_focus(self, which): # This duplicates some completion code, but I don't see a nicer way... assert which in ['prev', 'next'], which selmodel = self._file_view.selectionModel() parent = self._file_view.rootIndex() first_index = self._file_model.index(0, 0, parent) row = self._file_model.rowCount(parent) - 1 last_index = self._file_model.index(row, 0, parent) if not first_index.isValid(): # No entries return assert last_index.isValid() idx = selmodel.currentIndex() if not idx.isValid(): # No item selected yet idx = last_index if which == 'prev' else first_index elif which == 'prev': idx = self._file_view.indexAbove(idx) else: assert which == 'next', which idx = self._file_view.indexBelow(idx) # wrap around if we arrived at beginning/end if not idx.isValid(): idx = last_index if which == 'prev' else first_index selmodel.setCurrentIndex( idx, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows) self._insert_path(idx, clicked=False) def _allowed_commands(self): return [('prompt-accept', 'Accept'), ('leave-mode', 'Abort')]
class SessionParamWidget(Qt.QWidget): def __init__(self, parent=None): Qt.QWidget.__init__(self, parent) self.file_model = QFileSystemModel() def set_directory(self,directory): self.directory = directory self.file_model.setRootPath(directory) def setup_tree(self): self.folder_select_tree.setModel(self.file_model) self.folder_select_tree.setRootIndex(self.file_model.index(self.directory)); def connect_tree(self): self.folder_select_tree.clicked.connect(self.set_session_folder) def set_session_folder(self, index): indexItem = self.file_model.index(index.row(), 0, index.parent()) fileName = self.file_model.fileName(indexItem) filePath = self.file_model.filePath(indexItem) print(fileName) print(filePath)
class FileTree(QWidget): def __init__(self, defaultfolder=r'c:\Zen_Output'): super(QWidget, self).__init__() filter = ['*.czi', '*.ome.tiff', '*ome.tif' '*.tiff' '*.tif'] # define the style for the FileTree via s style sheet self.setStyleSheet(""" QTreeView::item { background-color: rgb(38, 41, 48); font-weight: bold; } QTreeView::item::selected { background-color: rgb(38, 41, 48); color: rgb(0, 255, 0); } QTreeView QHeaderView:section { background-color: rgb(38, 41, 48); color: rgb(255, 255, 255); } """) self.model = QFileSystemModel() self.model.setRootPath(defaultfolder) self.model.setFilter(QtCore.QDir.AllDirs | QDir.Files | QtCore.QDir.NoDotAndDotDot) self.model.setNameFilterDisables(False) self.model.setNameFilters(filter) self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setRootIndex(self.model.index(defaultfolder)) self.tree.setAnimated(True) self.tree.setIndentation(20) self.tree.setSortingEnabled(False) header = self.tree.header() header.setSectionResizeMode(QtWidgets.QHeaderView.ResizeToContents) windowLayout = QVBoxLayout() windowLayout.addWidget(self.tree) self.setLayout(windowLayout) self.tree.clicked.connect(self.on_treeView_clicked) @pyqtSlot() def on_treeView_clicked(self, index): indexItem = self.model.index(index.row(), 0, index.parent()) filename = self.model.fileName(indexItem) filepath = self.model.filePath(indexItem) # open the file when clicked print('Opening ImageFile : ', filepath) open_image_stack(filepath)
class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 file system view - pythonspot.com' self.left = 10 self.top = 10 self.width = 640 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.model = QFileSystemModel() r_inx = self.model.setRootPath(".") self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setAnimated(False) self.tree.setIndentation(15) self.tree.setSortingEnabled(True) self.tree.setWindowTitle("Dir View") self.tree.resize(640, 480) windowLayout = QVBoxLayout() windowLayout.addWidget(self.tree) self.setLayout(windowLayout) print(self.model.rootPath()) print(self.model.filePath(self.model.parent(r_inx))) index_temp = self.model.index(0, 0, QModelIndex()) print(self.model.fileName(index_temp)) self.show()
class MyGridFilesWidget(QWidget): def __init__(self, parent): super(QWidget, self).__init__(parent) start_dir = QStringListModel() start_dir = 'C:/ROBOCZY' self.model = QFileSystemModel() self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot | QDir.AllEntries) self.model.setNameFilters() self.model.setNameFilterDisables(0) #self.model.setRootPath(start_dir) #self.model.setRootPath(start_dir) self.tree = QTreeView() self.tree.setRootIndex(self.model.index(start_dir)) self.tree.setModel(self.model) self.tree.setAnimated(False) self.tree.setIndentation(20) self.tree.setSortingEnabled(True) self.tree.setWindowTitle("Dir View") self.tree.resize(640, 480) windowLayout = QVBoxLayout() windowLayout.addWidget(self.tree) self.setLayout(windowLayout)
def __init__(self, path, parent=None): super(MyQTreeView, self).__init__(parent) ppath = os.path.dirname(path) # parent of path self.setFrameStyle(0) #---- File System Model ---- sourceModel = QFileSystemModel() sourceModel.setRootPath(ppath) #---- Filter Proxy Model ---- proxyModel = MyQSortFilterProxyModel(path) proxyModel.setSourceModel(sourceModel) #---- Filter Proxy Model ---- self.setModel(proxyModel) self.setHeaderHidden(True) self.setRootIndex(proxyModel.mapFromSource(sourceModel.index(ppath))) #--- Hide All Header Sections Except First ---- header = self.header() for sec in range(1, header.count()): header.setSectionHidden(sec, True)
class FileChooser(QWidget): fileOpened = pyqtSignal(str) def __init__(self, parent=None): super().__init__(parent) self.folderBox = QComboBox(self) self.explorerTree = FileTreeView(self) self.explorerTree.doubleClickCallback = self._fileOpened self.explorerModel = QFileSystemModel(self) self.explorerModel.setFilter( QDir.AllDirs | QDir.Files | QDir.NoDotAndDotDot) self.explorerModel.setNameFilters(["*.py"]) self.explorerModel.setNameFilterDisables(False) self.explorerTree.setModel(self.explorerModel) for index in range(1, self.explorerModel.columnCount()): self.explorerTree.hideColumn(index) self.setCurrentFolder() self.folderBox.currentIndexChanged[int].connect( self.updateCurrentFolder) layout = QVBoxLayout(self) layout.addWidget(self.folderBox) layout.addWidget(self.explorerTree) layout.setContentsMargins(5, 5, 0, 0) def _fileOpened(self, modelIndex): path = self.explorerModel.filePath(modelIndex) if os.path.isfile(path): self.fileOpened.emit(path) def currentFolder(self): return self.explorerModel.rootPath() def setCurrentFolder(self, path=None): if path is None: app = QApplication.instance() path = app.getScriptsDirectory() else: assert os.path.isdir(path) self.explorerModel.setRootPath(path) self.explorerTree.setRootIndex(self.explorerModel.index(path)) self.folderBox.blockSignals(True) self.folderBox.clear() style = self.style() dirIcon = style.standardIcon(style.SP_DirIcon) self.folderBox.addItem(dirIcon, os.path.basename(path)) self.folderBox.insertSeparator(1) self.folderBox.addItem(self.tr("Browse…")) self.folderBox.setCurrentIndex(0) self.folderBox.blockSignals(False) def updateCurrentFolder(self, index): if index < self.folderBox.count() - 1: return path = QFileDialog.getExistingDirectory( self, self.tr("Choose Directory"), self.currentFolder(), QFileDialog.ShowDirsOnly) if path: QSettings().setValue("scripting/path", path) self.setCurrentFolder(path)
def update_file_tree(self): model = QFileSystemModel() model.setRootPath(self._root_dir) self.localFilesTreeView.setModel(model) local_selection_model = self.localFilesTreeView.selectionModel() local_selection_model.selectionChanged.connect(self.local_file_selection_changed) self.localFilesTreeView.setRootIndex(model.index(self._root_dir))
class FileBrowserWidget(QWidget): def __init__(self): super().__init__() self.initUI() def initUI(self): self.model = QFileSystemModel() self.model.setRootPath('') self.tree = QTreeView() self.tree.setModel(self.model) idx = self.model.index(BASE_DIR) self.tree.setRootIndex(idx) self.tree.setAnimated(False) self.tree.setIndentation(20) self.tree.setSortingEnabled(True) self.tree.hideColumn(2) self.tree.header().resizeSection(0,200) windowLayout = QVBoxLayout() windowLayout.addWidget(self.tree) self.setLayout(windowLayout)
def createDockWindows(self): dock = QDockWidget("Folders", self) dock.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea) #Code to Create FileView Colums and FolderTree self.FileView = QtWidgets.QColumnView() self.FileView.setGeometry(QtCore.QRect(240, 10, 291, 281)) self.FolderTree = QtWidgets.QTreeView() self.FolderTree.setGeometry(QtCore.QRect(10, 10, 221, 281)) FolderTree = self.FolderTree #FolderTree.hidecolumn(1),... ?? to show only name column #include FolderTree to a Dock at the left side dock.setWidget(FolderTree) self.addDockWidget(Qt.LeftDockWidgetArea, dock) #set the model and rootpath for filling the FolderTree from self.ui dirmodel = QFileSystemModel() #set filter to show only folders dirmodel.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs) dirmodel.setRootPath(rootpath) #filemodel and filter for only files on right side filemodel = QFileSystemModel() filemodel.setFilter(QDir.NoDotAndDotDot | QDir.Files) filemodel.setRootPath(rootpath) FolderView = self.FolderTree FolderView.setModel(dirmodel) FolderView.setRootIndex(dirmodel.index(rootpath)) FileView = self.FileView FileView.setModel(filemodel) dock = QDockWidget("Files", self) dock.setWidget(FileView) self.addDockWidget(Qt.RightDockWidgetArea, dock) #important lines for the connection, which does not work self.FolderTree.clicked['QModelIndex'].connect(self.setpathonclick)
def setup_file_explorer(tree, path=""): """Creates the file explorer rooted at a particular path. Args: tree (QTreeView): Tree to be populated tied to the file explorer. path (str, optional): Path to the root of the project. Returns: tuple[QFileSystemModel, QTreeView]: File system UI element and tied populated file tree. """ tree.setEnabled(os.path.isdir(path)) model = QFileSystemModel() model.setRootPath(path) tree.setModel(model) tree.setRootIndex(model.index(path)) # Resize column 0 (name) to content length, and stretch the rest to the size of the widget tree.header().setSectionResizeMode(0, QHeaderView.ResizeToContents) for i in range(1, model.columnCount()): tree.header().setSectionResizeMode(i, QHeaderView.Stretch) tree.setSortingEnabled(True) tree.sortByColumn(0, Qt.AscendingOrder) return model, tree
def __init__(self): super().__init__() self.setWindowTitle('Drag & Drop') # Даем разрешение на Drop self.setAcceptDrops(True) self.list_files = QListWidget() self.label_total_files = QLabel() model = QFileSystemModel() model.setRootPath(QDir.currentPath()) model.setReadOnly(False) self.tree = QTreeView() self.tree.setModel(model) self.tree.setRootIndex(model.index(QDir.currentPath())) self.tree.setSelectionMode(QTreeView.SingleSelection) self.tree.setDragDropMode(QTreeView.InternalMove) main_layout = QVBoxLayout() main_layout.addWidget(self.tree) main_layout.addWidget(QLabel('Перетащите файл:')) main_layout.addWidget(self.list_files) main_layout.addWidget(self.label_total_files) central_widget = QWidget() central_widget.setLayout(main_layout) self.setCentralWidget(central_widget) self._update_states()
class App(QWidget): def __init__(self): super().__init__() self.title = 'PyQt5 file system view' self.left = 100 self.top = 100 self.width = 1140 self.height = 480 self.initUI() def initUI(self): self.setWindowTitle(self.title) self.setGeometry(self.left, self.top, self.width, self.height) self.model = QFileSystemModel() self.model.setRootPath(QDir.rootPath()) self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setRootIndex(self.model.index(config['rgb_img_path'])) self.tree.setAnimated(False) self.tree.setIndentation(20) self.tree.setSortingEnabled(True) self.tree.setWindowTitle("Dir View") self.tree.resize(640, 480) self.tree.doubleClicked.connect(self.plot) windowLayout = QVBoxLayout() windowLayout.addWidget(self.tree) self.setLayout(windowLayout) self.m = PlotCanvas(self, width=5, height=4) self.m.move(640, 0) self.show() def plot(self, signal): file_path = self.tree.model().filePath(signal) sample_id = re.search(r'\d+', file_path.split('/')[-1]).group() self.m.plot(str(sample_id))
class DirectoryTree(QTreeView): def __init__(self): """ create directory tree """ super().__init__() self.layout = QHBoxLayout(self) self.model = QFileSystemModel() self.setModel(self.model) self.model.setRootPath(QDir.rootPath()) self.setIndentation(10) for i in range(1, 4): self.hideColumn(i) self.doubleClicked.connect(self.double_click) def set_root(self, path): """ set the directory the tree should index :param path: directory to index """ self.setRootIndex(self.model.index(path)) def double_click(self, signal): """ open a file when double clicked """ file_path = self.model.filePath(signal) tabs.tabs.new_tab(file_path)
class FileSystemView(QWidget): def __init__(self, dir_path): super().__init__() appWidth = 800 appHeight = 300 self.setWindowTitle('File System Viewer') self.setGeometry(300, 300, appWidth, appHeight) self.model = QFileSystemModel() self.model.setRootPath(dir_path) self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setRootIndex(self.model.index(dirPath)) self.tree.setColumnWidth(200, 250) self.tree.setAlternatingRowColors(True) layout = QVBoxLayout() layout.addWidget(self.tree) btnSelect = QPushButton("SELECT") layout.addWidget(btnSelect) self.setLayout(layout)
class DockFolders(QDockWidget, Ui_dock_folders): def __init__(self, parent): QDockWidget.__init__(self, parent=parent) self.setupUi(self) self.mw = parent # self.ed_path.setText(self.mw.cfg.value("root_path", defaultValue=QDir.homePath())) self.setupDirModel() self.tree.clicked.connect(self.onDirClicked) # self.btn_selectdir.clicked.connect(self.onButtonSelectDir) self.ed_path.returnPressed.connect(self.setupDirModel) def setupDirModel(self): """ Show folders on tree view """ path = self.ed_path.text() self.dirModel = QFileSystemModel() self.dirModel.setRootPath(path) self.dirModel.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) self.tree.setModel(self.dirModel) self.tree.setRootIndex(self.dirModel.index(path)) self.tree.hideColumn(1) self.tree.hideColumn(2) self.tree.hideColumn(3) self.tree.resizeColumnToContents(0) def onDirClicked(self, index): path = self.dirModel.fileInfo(index).absoluteFilePath() self.mw.loadAlbum(path)
def ls_current_dir(self): path_to_dir = self.current_dict[self.top.currentItem().text()][-1] # ls content of the current dirQt.CustomContextMenu lsdir = QFileSystemModel() lsdir.setRootPath(path_to_dir) self.tree.setModel(lsdir) self.tree.setRootIndex(lsdir.index(path_to_dir)) self.tree.setColumnWidth(0, 450)
def __initFilesView(self, model: QFileSystemModel): view = QTreeView() view.setEditTriggers(QTreeView.NoEditTriggers) view.hideColumn(1) view.hideColumn(3) view.setGeometry(0, 0, 10, 10) view.setModel(model) view.setRootIndex(model.index(str(model.rootDirectory()))) return view
class AssetBrowser(QMainWindow, Ui_MainWindow): asset_clicked = pyqtSignal(str, str, name='assetClicked') def __init__(self): super(AssetBrowser, self).__init__() self.setupUi(self) self.dir_model = QFileSystemModel() self.dir_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs) self.dir_model.setReadOnly(False) self.dir_view.setModel(self.dir_model) self.dir_view.hideColumn(1) self.dir_view.hideColumn(2) self.dir_view.hideColumn(3) self.file_model = QFileSystemModel() self.file_model.setFilter(QDir.NoDotAndDotDot | QDir.Files) self.file_model.setReadOnly(False) self.file_view.setModel(self.file_model) def open_project(self, project_dir): path = os.path.join(project_dir) self.dir_model.setRootPath(path) self.file_model.setRootPath(path) self.dir_view.setRootIndex(self.dir_model.index(path)) self.file_view.setRootIndex(self.file_model.index(path)) def dir_clicked(self, idx): path = self.dir_model.fileInfo(idx).absoluteFilePath() self.file_view.setRootIndex(self.file_model.setRootPath(path)) def file_doubleclicked(self, idx): fileinfo = self.file_model.fileInfo(idx) path = fileinfo.absoluteFilePath() ext = fileinfo.suffix() self.asset_clicked.emit(path, ext)
def init_tree(self): model = QFileSystemModel() path = os.path.dirname(os.path.realpath(__file__)) + os.path.sep + 'notes' model.setRootPath(path) self.tv_notes.setModel(model) self.tv_notes.setRootIndex(model.index(path)) self.tv_notes.setHeaderHidden(True) self.tv_notes.resizeColumnToContents(0) self.tv_notes.setColumnHidden(1, True) self.tv_notes.setColumnHidden(2, True) self.tv_notes.setColumnHidden(3, True)
def icon(self): fnisPath = self.__organizer.pluginSetting(self.name(), "fnis-path") if os.path.exists(fnisPath): # We can't directly grab the icon from an executable, but this seems like the simplest alternative. fin = QFileInfo(fnisPath) model = QFileSystemModel() model.setRootPath(fin.path()) return model.fileIcon(model.index(fin.filePath())) else: # Fall back to where the user might have put an icon manually. return QIcon("plugins/FNIS.ico")
def SetTreeWedgit(self): Model = QFileSystemModel() Model.setRootPath(QDir.currentPath()) self.treeView.setModel(Model) self.treeView.setRootIndex(Model.index(QDir.currentPath())) self.treeView.setAnimated(False) self.treeView.setIndentation(20) self.treeView.setSortingEnabled(False) self.treeView.hideColumn(1) self.treeView.hideColumn(2) self.treeView.hideColumn(3) self.treeView.doubleClicked.connect(self.TreeViewDoubleClicked)
def initRootDir(self,indexDir): if not indexDir: return self.indexDir = indexDir model = QFileSystemModel() model.setRootPath('') self.setModel(model) self.setAnimated(False) self.setIndentation(20) self.setSortingEnabled(True) self.setRootIndex(model.index(self.indexDir)) for i in range(1,model.columnCount()): self.hideColumn(i)
class SelectFolderWindow(QtGui.QDialog, Ui_Session_Dialog): def __init__(self, directory, parent=None): super(SelectFolderWindow, self).__init__(parent) self.setupUi(self) self.folder_name = None self.folder_path = None self.file_model = QFileSystemModel() self.directory = directory self.file_model.setRootPath(directory) self.folder_tree.setModel(self.file_model) self.folder_tree.setRootIndex(self.file_model.index(self.directory)) self.folder_tree.clicked.connect(self.set_session_folder) def update_file_model(self, new_dir): self.directory = new_dir self.file_model.setRootPath(new_dir) def set_session_folder(self, index): indexItem = self.file_model.index(index.row(), 0, index.parent()) self.folder_name = self.file_model.fileName(indexItem) self.folder_path = self.file_model.filePath(indexItem) self.selected_session.setText(self.folder_path)
def directory(app): #app = QApplication(sys.argv) QCoreApplication.setApplicationVersion(QT_VERSION_STR) parser = QCommandLineParser() parser.setApplicationDescription("File Directory") parser.addHelpOption() parser.addVersionOption() dontUseCustomDirectoryIconsOption = QCommandLineOption( 'C', "Set QFileIconProvider.DontUseCustomDirectoryIcons") parser.addOption(dontUseCustomDirectoryIconsOption) parser.addPositionalArgument('', "The directory to start in.") parser.process(app) try: rootPath = parser.positionalArguments().pop(0) except IndexError: rootPath = None model = QFileSystemModel() model.setRootPath('') filter = ['*.db'] #filtering out just by db model.setNameFilters(filter) model.setNameFilterDisables(0) #Only show the filtered .db paths #filename = model.filePath() #print(filename) if parser.isSet(dontUseCustomDirectoryIconsOption): model.iconProvider().setOptions( QFileIconProvider.DontUseCustomDirectoryIcons) tree = QTreeView() tree.setModel(model) if rootPath is not None: rootIndex = model.index(QDir.cleanPath(rootPath)) if rootIndex.isValid(): tree.setRootIndex(rootIndex) # Demonstrating look and feel features. tree.setAnimated(False) tree.setIndentation(20) tree.setSortingEnabled(True) availableSize = QApplication.desktop().availableGeometry(tree).size() tree.resize(availableSize / 2) tree.setColumnWidth(0, tree.width() / 3) tree.setWindowTitle("Directory View") tree.show() sys.exit(app.exec_())
def setUpFileExplorer(self, folder): tvFileModel = QFileSystemModel() tvFileModel.setRootPath(folder) self.tvFileSystem.setModel(tvFileModel) self.tvFileSystem.setRootIndex(tvFileModel.index(folder)) self.tvFileSystem.hideColumn(1) self.tvFileSystem.hideColumn(2) self.tvFileSystem.hideColumn(3) self.tvFileSystem.setContextMenuPolicy(Qt.CustomContextMenu) self.tvFileSystem.customContextMenuRequested.connect( self.fileSystemMenu) # self.tvFileSystem.doubleClicked.connect(self.tvFileSystem_doubleClicked) self.setPathDisplay(folder)
def setup_file_view(view, encoded): d = path.join(getcwd(), 'docs') fs_model = QFileSystemModel(view) fs_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs | QDir.AllEntries) fs_model.setRootPath(d) model = SortFilterModel(encoded) model.setSourceModel(fs_model) view.setModel(model) view.setRootIndex(model.mapFromSource(fs_model.index(d))) view.setColumnHidden(2, True) view.sortByColumn(0, Qt.AscendingOrder) for i in range(0, 3): view.header().setSectionResizeMode(i, QHeaderView.ResizeToContents) return fs_model, model
def __init__(self, win): Ui_MainWindow.__init__(self) self.window = win self.setupUi(win) qfs = QFileSystemModel(self.treeView) exclude = ExcludeSomeNamesModel() exclude.setSourceModel(qfs) self.treeView.setModel(exclude) qfs.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot | QDir.Files) if sys.platform == 'darwin': qfs.setRootPath("/Volumes") self.treeView.setRootIndex( exclude.mapFromSource(qfs.index("/Volumes"))) elif sys.platform == 'win32': qfs.setRootPath("\\") self.treeView.setRootIndex(exclude.mapFromSource(qfs.index("\\"))) else: raise UnsupportedPlatform(sys.platform) self.treeView.doubleClicked.connect(self.volumeDoubleClicked) self.qfs = qfs self.exclude = exclude self.treeView.setSortingEnabled(True) self.treeView.setColumnWidth(0, 300) self.treeView.setItemsExpandable(False) self.treeView.setRootIsDecorated(False) self.openFileButton.clicked.connect(self.openFileButtonClicked) self.aboutButton.clicked.connect(self.aboutButtonClicked) for elem in range(1, 4): self.treeView.hideColumn(elem)
class FileSystemTreeView(QTreeView, QDockWidget): def __init__(self, parent=None): super().__init__(parent=parent) self.main_window = parent self.fileSystemModel = QFileSystemModel() self.fileSystemModel.setRootPath('.') self.setModel(self.fileSystemModel) self.setRootIndex(self.fileSystemModel.index('.')) # 隐藏size,date等列 self.setColumnWidth(0, 200) self.setColumnHidden(1, True) self.setColumnHidden(2, True) self.setColumnHidden(3, True) # 不显示标题栏 self.header().hide() # 设置动画 self.setAnimated(True) # 选中不显示虚线 self.setFocusPolicy(Qt.NoFocus) self.setMinimumWidth(200) def alter_dir(self, path): self.setRootIndex(self.fileSystemModel.index(path)) self.show()
def refreshDir(self): directory = self.model.getDirectoryName() self.lineEdit_SearchDir.setText(directory) fileSystemModel = QFileSystemModel() fileSystemModel.setRootPath('') self.treeViewDirectory.setModel(fileSystemModel) self.treeViewDirectory.setRootIndex(fileSystemModel.index(directory)) self.treeViewDirectory.setAnimated(False) self.treeViewDirectory.setIndentation(20) self.treeViewDirectory.setSortingEnabled(True) self.treeViewDirectory.sortByColumn(0, Qt.AscendingOrder) self.treeViewDirectory.setWindowTitle("Dir View") self.treeViewDirectory.selectionModel().currentChanged.connect(self.on_treeViewDirectoryClicked)
class DirTreeView(QTreeView): """ A widget class used to display the contents of an Informatic project source directory. """ newSelection = pyqtSignal([list]) def __init__(self, parent=None, rootdir=None): """ The rootdir keyword argument is a filepath for a directory initialized as the root directory whose contents are displayed by the widget. """ # Invoke the QTreeView constructor super().__init__(parent) self.setSizePolicy(QSizePolicy.Preferred, QSizePolicy.Preferred) # The widget's contents are based on a file system model self.dirTree = QFileSystemModel() # Display only files with filename extensions commonly used for Inform 6 # source files self.dirTree.setNameFilterDisables(False) self.dirTree.setNameFilters(['*.inf', '*.i6', '*.h']) self.dirTree.setRootPath(rootdir) self.setModel(self.dirTree) self.cd(rootdir) # Hide all but the first column, which holds the filename for column in range(1, self.dirTree.columnCount()): self.hideColumn(column) def cd(self, path): """ Takes one argument, path, a directory filepath, and changes the root directory displayed by the widget to the directory at that filepath. """ self.setRootIndex(self.dirTree.index(path)) def selectionChanged(self, selected, deselected): """ Emits the newSelection signal with a list of selected items whenever the selection of items in the file tree is changed. """ self.newSelection.emit(selected.indexes())
def __init__(self, parent=None): QMainWindow.__init__(self) super(MyWindowClass, self).__init__(parent) self.installEventFilter(self) self.setupUi(self) # self.QSciEditor = tabEditor(parent=self) # self.QSciEditor.setIndentationGuides(True) model = QFileSystemModel() model.setRootPath(path_of_me) self.label.setText(os.path.basename(path_of_me)) self.treeView.setModel(model) self.treeView.setRootIndex(model.index(path_of_me)) self.treeView.hideColumn(1) self.treeView.hideColumn(2) self.treeView.hideColumn(3) self.treeView.setHeaderHidden(True) self.treeView.doubleClicked.connect(self.tabHandler) self.terminal = embterminal(self.pageLayout) # self.process = QtCore.QProcess(self) # self.terminal = QtWidgets.QWidget(self) # self.pageLayout.addWidget(self.terminal) # self.process.start('xterm', ['-into', str(self.terminal.winId())]) # self.page.setLayout(layout) # self.infoBox.resize(531,0) # self.pageLayout self.tabWidget.tabCloseRequested.connect(self.delTab) self.shortcuts = [] for key in self.keybindings: self.shortcuts.append(QShortcut(self)) self.shortcuts[-1].setKey(key[0]) self.shortcuts[-1].activated.connect(getattr(self, key[1])) self.treeOutline.title = "Outline View" # Probably treeOutline will be a discrete class soon.. self.treeOutline.setContextMenuPolicy(Qt.CustomContextMenu) self.treeOutline.customContextMenuRequested.connect(self.openMenu) self.treeOutline.clicked.connect(self.outline_clicked) self.cleanButton.clicked.connect(self.clean) # self.gridLayout.addWidget(self.QSciEditor) self.ast = AstParser() self.show()
class FileBrowser(QWidget): def __init__(self, dirPath): super(FileBrowser, self).__init__() appWidth = 800 appHeight = 800 self.setWindowTitle('File Browser') self.setGeometry(300, 300, appWidth, appHeight) self.model = QFileSystemModel() self.model.setRootPath(dirPath) self.tree = QTreeView() self.tree.setModel(self.model) self.tree.setRootIndex(self.model.index(dirPath)) self.tree.setColumnWidth(0, 250) self.tree.setAlternatingRowColors(True) layout = QVBoxLayout() layout.addWidget(self.tree) self.setLayout(layout)
def __init__(self, parent=None): QWidget.__init__(self, parent=parent) self.setFixedSize(300, 250) layout = QVBoxLayout() model = QFileSystemModel() model.setRootPath(QDir.currentPath()) list = QListView() list.setModel(model) list.setRootIndex(model.index( QDir.rootPath())) # фильтруем данные из модели!!! layout.addWidget(list) self.setLayout(layout)
def load_dir(self, dir_path): if dir_path == self.dir_path: return self.dir_path = dir_path model = QFileSystemModel() model.setRootPath(dir_path) self.setModel(model) index_root = model.index(model.rootPath()) self.setRootIndex(index_root) # hide unwanted info self.hideColumn(1) self.hideColumn(2) self.hideColumn(3) self.setHeaderHidden(True)
class filetree(QTreeView): def __init__(self): super().__init__() """creates a file tree widget""" self.model = QFileSystemModel() self.model.setRootPath('/home/inbal') self.setDragEnabled(True) self.model.removeColumn(1) self.model.removeColumn(3) self.setModel(self.model) self.setRootIndex(self.model.index('/home/')) self.hideColumn(1) self.hideColumn(2) self.hideColumn(3) self.setAnimated(True) self.setIndentation(20) self.setSortingEnabled(True)
def load_tree(self, project): """Load the tree view on the right based on the project selected.""" qfsm = QFileSystemModel() qfsm.setRootPath(project.path) load_index = qfsm.index(qfsm.rootPath()) qfsm.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot) qfsm.setNameFilterDisables(False) pext = ["*{0}".format(x) for x in project.extensions] qfsm.setNameFilters(pext) self._tree.setModel(qfsm) self._tree.setRootIndex(load_index) t_header = self._tree.header() t_header.setHorizontalScrollMode(QAbstractItemView.ScrollPerPixel) t_header.setSectionResizeMode(0, QHeaderView.Stretch) t_header.setStretchLastSection(False) t_header.setClickable(True) self._tree.hideColumn(1) # Size self._tree.hideColumn(2) # Type self._tree.hideColumn(3) # Modification date
class MainWindow(QMainWindow): inputReceived = pyqtSignal(str) def __init__(self, parent=None): super(MainWindow, self).__init__(parent) self.ui = Ui_MainWindow() self.ui.setupUi(self) # Left Browser tabs self.ui.tabWidgetBrowser.removeTab(1) self.ui.tabWidgetBrowser.removeTab(1) self.ui.tabWidgetBrowser.setTabsClosable(True) self.ui.tabWidgetBrowser.tabCloseRequested.connect(self.closeBrowserTab) self.ui.tabWidgetBrowser.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetBrowser)) # Left tree views self.fileTreeModel = QFileSystemModel(self) self.fileTreeModel.setRootPath(QDir.currentPath() + QDir.separator() + 'test') self.ui.treeViewFile.setModel(self.fileTreeModel) self.ui.treeViewFile.setRootIndex(self.fileTreeModel.index(QDir.currentPath() + QDir.separator() + 'test')) self.ui.treeViewFile.hideColumn(1) self.ui.treeViewFile.hideColumn(2) self.ui.treeViewFile.hideColumn(3) self.ui.treeViewFile.doubleClicked.connect(self.openFileFromTree) self.ui.treeViewFile.setAnimated(True) self.ui.treeViewSyntax.setAnimated(True) self.ui.treeViewToken.setAnimated(True) self.ui.treeViewFile.setHeaderHidden(True) self.ui.treeViewSyntax.setHeaderHidden(True) self.ui.treeViewToken.setHeaderHidden(True) # Editor tabs self.currentEditor = self.ui.codeEditor self.currentEditor.file = None self.currentEditorTab = self.ui.tabEditor self.openedEditors = [self.currentEditor] self.openedEditorTabs = [self.currentEditorTab] self.currentEditor.setFocus() # set focus self.ui.tabWidgetEditor.tabCloseRequested.connect(self.closeEditorTab) self.ui.tabWidgetEditor.tabBarClicked.connect(self.switchEditorTab) self.ui.tabWidgetEditor.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetEditor)) # Bottom console font = QFont() font.setFamily("Courier") font.setStyleHint(QFont.Monospace) font.setFixedPitch(True) font.setPointSize(10) self.ui.console.setFont(font) self.ui.console.setReadOnly(True) self.waitInputCond = QWaitCondition() self.oldConsoleText = None # Bottom output tabs self.ui.tabWidgetOutput.hide() self.ui.tabWidgetOutput.tabCloseRequested.connect(self.closeOutputTab) self.ui.tabWidgetOutput.tabBarDoubleClicked.connect(lambda: self.maximizeTabs(self.ui.tabWidgetOutput)) self.ui.tabWidgetOutput.setTabText(0, 'Console') # Previous opened tabs,for maximizing self.preOpenedTabs = None # Initial size of inner splitter self.ui.splitterInner.setSizes([180, 459 * 2 - 180]) # Menu "File" self.ui.actionOpen.triggered.connect(self.openFile) self.ui.actionNew.triggered.connect(self.newFile) self.ui.actionSave.triggered.connect(self.saveFile) self.ui.actionSaveAs.triggered.connect(self.saveFileAs) self.ui.actionQuit.triggered.connect(self.close) # Menu "Edit" self.connectMenuEditSlots() # Menu "View" self.ui.menuView.triggered.connect(self.manageMenuView) self.ui.actionAboutQt.triggered.connect(QApplication.aboutQt) # Menu "Run" self.ui.actionRun.triggered.connect(self.run) self.ui.actionBuild.triggered.connect(self.runCompile) self.ui.actionShowStable.triggered.connect(self.runSemantic) self.ui.actionRunParser.triggered.connect(self.runParser) self.ui.actionRunLexer.triggered.connect(self.runLexer) @pyqtSlot(bool) def runLexer(self, checked): """ Run lexer and present result on self.ui.tabToken Tree :return: """ p = self.genParser(Parser.mode_lexer) tokenNode = p.lexse() if p else None if not tokenNode: self.endEcho(False) return self.showBrowserTree(self.ui.tabToken, tokenNode) self.endEcho(True) @pyqtSlot(bool) def runParser(self, checked): """ Run parser and present result on self.ui.tabSyntax Tree :return: """ # Begin parse p = self.genParser(Parser.mode_parser) result = p.parse() if p else None if not result: self.endEcho(False) return syntaxNode, tokenNode = result # self.showBrowserTree(self.ui.tabToken, tokenNode) self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.showBrowserTree(self.ui.tabSyntax, syntaxNode) self.endEcho(True) @pyqtSlot(bool) def runSemantic(self, checked): """ run semantics analysing and print symbol table :return: """ p = self.genParser(Parser.mode_stable) result = p.semantic() if p else None if not result: self.endEcho(False) return stable, syntaxNode, tokenNode = result self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.ui.treeViewSyntax.setModel(TreeModel(syntaxNode)) self.endEcho(True) @pyqtSlot(bool) def runCompile(self, checked): """ Run compiler and print Intermediate code :return: """ p = self.genParser(Parser.mode_compile) result = p.compile() if p else None if not result: self.endEcho(False) return codes, stable, syntaxNode, tokenNode = result self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.ui.treeViewSyntax.setModel(TreeModel(syntaxNode)) self.endEcho(True) @pyqtSlot(bool) def run(self, checked): """ compile and run the source code compile in main thread and run in a worker thread """ p = self.genParser(Parser.mode_execute) result = p.compile() if p else None if not result: self.endEcho(False) return codes, stable, syntaxNode, tokenNode = result self.ui.treeViewToken.setModel(TreeModel(tokenNode)) self.ui.treeViewSyntax.setModel(TreeModel(syntaxNode)) console = Console(self.ui.console, parent=self, waitCond=self.waitInputCond) console.update.connect(self.updateOutput) self.inputReceived.connect(console.receivedInput) self.ui.console.blockCountChanged.connect(self.waitInput) self.ui.console.textChanged.connect(self.disableBack) interp = Interpreter(codes, stdin=console, stdout=console, stderr=console) thread = ExecuteThread(interp.inter, self) thread.start() def genParser(self, mode=Parser.mode_execute): """ Generate a parser instance :param mode: :return: """ if not self.saveFile(): return self.showOutputPanel() self.ui.actionViewConsole.setChecked(True) self.beginEcho() stdin = open(self.currentEditor.file, 'r') console = Console(self.ui.console, parent=self) console.update.connect(self.updateOutput) return Parser(stdin, stdout=console, stderr=console, mode=mode) def beginEcho(self): self.updateOutput('%s\n' % self.currentEditor.file) def endEcho(self, success=True): msg = 'successfully' if success else 'unsuccessfully' self.updateOutput('Process finished %s\n' % msg) @pyqtSlot(str) def updateOutput(self, content): """ Update bottom text browser when content is writen to it. :param content: :return: """ self.ui.console.moveCursor(QTextCursor.End) self.ui.console.insertPlainText('%s' % content) self.oldConsoleText = self.ui.console.toPlainText() @pyqtSlot(int) def waitInput(self, newBlockCount): """ :param newBlockCount: line count :return: """ if not self.ui.console.isReadOnly(): self.inputReceived.emit(self.ui.console.toPlainText() .replace(self.oldConsoleText, '')) self.waitInputCond.wakeAll() self.ui.console.setReadOnly(True) @pyqtSlot() def disableBack(self): """ disable backspace when waiting for input :return: """ if not self.ui.console.isReadOnly(): if len(self.oldConsoleText) > len(self.ui.console.toPlainText()): self.ui.console.setPlainText(self.oldConsoleText) self.ui.console.moveCursor(QTextCursor.End) def closeEvent(self, event): """ Override. When Close Event Triggered. Ask user for saving modified files :param event: :return: """ for i in range(len(self.openedEditors)): editor = self.openedEditors[i] editorTab = self.openedEditorTabs[i] if editor.document().isModified(): name = ntpath.basename(editor.file) if editor.file else 'New File' ret = QMessageBox.warning( self, name, 'The document has been modified.\nDo you want to save your changes?', QMessageBox.Save | QMessageBox.Discard | QMessageBox.Cancel) if ret == QMessageBox.Save: event.accept() if self.saveFile() else event.ignore() elif ret == QMessageBox.Discard: index = self.ui.tabWidgetEditor.indexOf(editorTab) self.ui.tabWidgetEditor.removeTab(index) event.accept() else: event.ignore() def showOutputPanel(self): """ Clear previous output and show the ouput panel :return: """ self.ui.console.clear() self.ui.tabWidgetOutput.show() def showBrowserTree(self, tab, rootNode): """ Show treeView on tabWidgetBrowser :param tab: :param rootNode: """ model = TreeModel(rootNode) if tab == self.ui.tabSyntax: treeView = self.ui.treeViewSyntax name = 'Syntax' self.ui.actionViewSystaxTree.setChecked(True) else: treeView = self.ui.treeViewToken name = 'Token' self.ui.actionViewTokenTree.setChecked(True) treeView.setModel(model) # show the tab index = self.ui.tabWidgetBrowser.indexOf(tab) if index == -1: self.ui.tabWidgetBrowser.addTab(tab, name) index = self.ui.tabWidgetBrowser.indexOf(tab) self.ui.tabWidgetBrowser.setCurrentIndex(index) self.addjustBrowserWidth() def connectMenuEditSlots(self): """ set menu "Edit" signals connect to current editor slots :return: """ self.ui.actionCopy.triggered.connect(self.currentEditor.copy) self.ui.actionCut.triggered.connect(self.currentEditor.cut) self.ui.actionPaste.triggered.connect(self.currentEditor.paste) self.ui.actionUndo.triggered.connect(self.currentEditor.undo) self.ui.actionRedo.triggered.connect(self.currentEditor.redo) self.ui.actionSelectAll.triggered.connect(self.currentEditor.selectAll) def disconnectMenuEditSlots(self): """ disconnect menu "Edit" signals :return: """ self.ui.actionCopy.triggered.disconnect(self.currentEditor.copy) self.ui.actionCut.triggered.disconnect(self.currentEditor.cut) self.ui.actionPaste.triggered.disconnect(self.currentEditor.paste) self.ui.actionUndo.triggered.disconnect(self.currentEditor.undo) self.ui.actionRedo.triggered.disconnect(self.currentEditor.redo) self.ui.actionSelectAll.triggered.disconnect(self.currentEditor.selectAll) def createEditorTab(self): """ Create a new Editor tab and set as current editor Should reconnect the signal on menu 'Edit' actions :return: """ # add a new editor self.currentEditorTab = QtWidgets.QWidget() horizontalLayout = QtWidgets.QHBoxLayout(self.currentEditorTab) horizontalLayout.setContentsMargins(0, 0, 0, 0) horizontalLayout.setSpacing(6) codeEditor = CodeEditor(self.currentEditorTab) horizontalLayout.addWidget(codeEditor) self.ui.tabWidgetEditor.addTab(self.currentEditorTab, "") # disconnect signals self.disconnectMenuEditSlots() # change current tab and editors self.currentEditor = codeEditor self.currentEditor.file = None self.openedEditors.append(self.currentEditor) self.openedEditorTabs.append(self.currentEditorTab) # connect signals self.connectMenuEditSlots() # set tab closeable if len(self.openedEditorTabs) > 1: self.ui.tabWidgetEditor.setTabsClosable(True) @pyqtSlot(int) def switchEditorTab(self, index): """ Switch current active editor tab to index Should reconnect the signal on menu 'Edit' actions :param index: :return: """ self.disconnectMenuEditSlots() self.currentEditorTab = self.openedEditorTabs[index] self.currentEditor = self.openedEditors[index] self.connectMenuEditSlots() @pyqtSlot(int) def closeEditorTab(self, index): """ Triggered when closing the editor tab at index requested :param index: :return: """ self.ui.tabWidgetEditor.removeTab(index) self.openedEditorTabs.pop(index) self.openedEditors.pop(index) self.switchEditorTab(0) # choose the beginning tab as current active if len(self.openedEditorTabs) == 1: self.ui.tabWidgetEditor.setTabsClosable(False) @pyqtSlot(int) def closeBrowserTab(self, index): """ Close Left Browser Tab at index :param index: :return: """ # make menu "View" corresponding w = self.ui.tabWidgetBrowser.widget(index) if w == self.ui.tabFile: self.ui.actionViewFiles.setChecked(False) elif w == self.ui.tabToken: self.ui.actionViewTokenTree.setChecked(False) else: self.ui.actionViewSystaxTree.setChecked(False) # remove tab self.ui.tabWidgetBrowser.removeTab(index) if self.ui.tabWidgetBrowser.count() == 0: self.ui.tabWidgetBrowser.hide() @pyqtSlot(int) def closeOutputTab(self, index): """ Close(hide) the output tab widget :param index: """ # make menu "View" corresponding self.ui.actionViewConsole.setChecked(False) self.ui.tabWidgetOutput.hide() def recoverTabWidgets(self): """ recover tabs when cancel maximizing :return: """ for tab in self.preOpenedTabs: tab.show() self.preOpenedTabs = None def storeOpenedTabs(self): """ store tabs opened before maximize :return: """ self.preOpenedTabs = [] if not self.ui.tabWidgetOutput.isHidden(): self.preOpenedTabs.append(self.ui.tabWidgetOutput) if not self.ui.tabWidgetEditor.isHidden(): self.preOpenedTabs.append(self.ui.tabWidgetEditor) if not self.ui.tabWidgetBrowser.isHidden(): self.preOpenedTabs.append(self.ui.tabWidgetBrowser) def maximizeTabs(self, widget): if self.preOpenedTabs: self.recoverTabWidgets() else: self.storeOpenedTabs() for w in [self.ui.tabWidgetBrowser, self.ui.tabWidgetOutput, self.ui.tabWidgetEditor]: if w != widget: w.hide() @pyqtSlot(QAction) def manageMenuView(self, action): """ Handle the action on menu "View" :param action: :return: """ if action == self.ui.actionViewToolbar: self.ui.toolBar.show() if action.isChecked() else self.ui.toolBar.hide() return pair = { self.ui.actionViewFiles: (self.ui.tabWidgetBrowser, self.ui.tabFile, 'File'), self.ui.actionViewTokenTree: (self.ui.tabWidgetBrowser, self.ui.tabToken, 'Token'), self.ui.actionViewSystaxTree: (self.ui.tabWidgetBrowser, self.ui.tabSyntax, 'Syntax'), self.ui.actionViewConsole: (self.ui.tabWidgetOutput, self.ui.tabConsole, 'Console'), } p = pair[action] widget = p[0] tab = p[1] name = p[2] if action.isChecked(): widget.addTab(tab, name) widget.setCurrentWidget(tab) if widget == self.ui.tabWidgetBrowser: # reset tab inner splitter size self.addjustBrowserWidth() if widget.isHidden(): widget.show() else: widget.removeTab( widget.indexOf(tab)) if widget.count() == 0: widget.hide() def addjustBrowserWidth(self): w = self.ui.tabWidgetBrowser.count() * 80 self.ui.splitterInner.setSizes([w, self.ui.splitterInner.width() - w]) @pyqtSlot(bool) def openFile(self, checked=True, path=None): """ Open a new file. If current editor is associated with a file or its content is not null, Then create a new editor tab :return: """ path = QFileDialog.getOpenFileName()[0] if not path else path if len(path) != 0: qfile = QFile(path) if not qfile.open(QFile.ReadOnly or QFile.Text): QMessageBox.warning(self, 'Application', 'Cannot read file %s:\n%s.' % (path, qfile.errorString())) return with open(path, 'r') as _file: content = _file.read() if self.currentEditor.file or len(self.currentEditor.document().toPlainText()) > 0: self.createEditorTab() # associate file on disk with editor self.currentEditor.file = path # update tab name index = self.ui.tabWidgetEditor.indexOf(self.currentEditorTab) _translate = QCoreApplication.translate self.ui.tabWidgetEditor.setTabText( index, _translate("MainWindow", ntpath.basename(path))) self.ui.tabWidgetEditor.setCurrentIndex(index) self.currentEditor.setPlainText(content) @pyqtSlot(int) def openFileFromTree(self, index): f = self.fileTreeModel.fileInfo(index) if f.isFile(): self.openFile(path=f.filePath()) @pyqtSlot(bool) def newFile(self, checked): """ create a new editor tab :param action: :return: """ self.createEditorTab() index = self.ui.tabWidgetEditor.indexOf(self.currentEditorTab) _translate = QCoreApplication.translate self.ui.tabWidgetEditor.setTabText( index, _translate("MainWindow", 'New File')) self.ui.tabWidgetEditor.setCurrentIndex(index) @pyqtSlot(bool) def saveFile(self, checked=None): """ Save file. If current editor is associated with a file on the disk, then save it. Or save file as... :param checked: :return: Saved or canceled """ if self.currentEditor.file: if self.currentEditor.document().isModified(): with open(self.currentEditor.file, 'w') as f: f.write(self.currentEditor.document().toPlainText()) self.currentEditor.document().setModified(False) return True else: return self.saveFileAs() @pyqtSlot(bool) def saveFileAs(self, checked=None): """ Save File As... :param checked: :return: If saved or canceled """ dialog = QFileDialog() dialog.setWindowModality(Qt.WindowModal) dialog.setAcceptMode(QFileDialog.AcceptSave) if dialog.exec_(): filepath = dialog.selectedFiles()[0] with open(filepath, 'w') as f: f.write(self.currentEditor.document().toPlainText()) self.currentEditor.document().setModified(False) self.currentEditor.file = filepath return True else: return False
class MainView(QMainWindow): resizeCompleted = pyqtSignal() def __init__(self, model, controller, image_path): self.settings = SettingsModel() self.slideshow = SlideshowModel() self.model = model self.canvas = self.model.canvas self.main_controller = controller self.canvas_controller = CanvasController(self.canvas) super(MainView, self).__init__() self.build_ui() self.center_ui() # Resize timer to prevent laggy updates self.resize_timer = None self.resizeCompleted.connect(self.resize_completed) # Slideshow if self.settings.get('Slideshow', 'reverse') == 'True': self.slideshow.updateSignal.connect(self.on_previous_item) else: self.slideshow.updateSignal.connect(self.on_next_item) self.model.subscribe_update_func(self.update_ui_from_model) self.arguments = { 'image_path': image_path } def build_ui(self): self.ui = Ui_Hitagi() self.ui.setupUi(self) # File menu self.ui.actionSet_as_wallpaper.triggered.connect(self.on_set_as_wallpaper) self.ui.actionCopy_to_clipboard.triggered.connect(self.on_clipboard) self.ui.actionOpen_current_directory.triggered.connect(self.on_current_dir) self.ui.actionOptions.triggered.connect(self.on_options) self.ui.actionExit.triggered.connect(self.on_close) # Folder menu self.ui.actionOpen_next.triggered.connect(self.on_next_item) self.ui.actionOpen_previous.triggered.connect(self.on_previous_item) self.ui.actionChange_directory.triggered.connect(self.on_change_directory) self.ui.actionSlideshow.triggered.connect(self.on_slideshow) # View menu self.ui.actionZoom_in.triggered.connect(self.on_zoom_in) self.ui.actionZoom_out.triggered.connect(self.on_zoom_out) self.ui.actionOriginal_size.triggered.connect(self.on_zoom_original) self.ui.actionRotate_clockwise.triggered.connect(self.on_rotate_clockwise) self.ui.actionRotate_counterclockwise.triggered.connect(self.on_rotate_counterclockwise) self.ui.actionFlip_horizontally.triggered.connect(self.on_flip_horizontal) self.ui.actionFlip_vertically.triggered.connect(self.on_flip_vertical) self.ui.actionFit_image_width.triggered.connect(self.on_scale_image_to_width) self.ui.actionFit_image_height.triggered.connect(self.on_scale_image_to_height) self.ui.actionFile_list.triggered.connect(self.on_toggle_filelist) self.ui.actionFullscreen.triggered.connect(self.on_fullscreen) # Favorite menu self.ui.actionAdd_to_favorites.triggered.connect(self.on_add_to_favorites) self.ui.actionRemove_from_favorites.triggered.connect(self.on_remove_from_favorites) # Help menu self.ui.actionChangelog.triggered.connect(self.on_changelog) self.ui.actionAbout.triggered.connect(self.on_about) # Load stylesheet stylesheet_dir = "resources/hitagi.stylesheet" with open(stylesheet_dir, "r") as sh: self.setStyleSheet(sh.read()) # File listing self.file_model = QFileSystemModel() self.file_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs | QDir.Files) self.file_model.setNameFilters(['*.bmp', '*.gif', '*.jpg', '*.jpeg', '*.png', '*.png', '*.pbm', '*.pgm', '*.ppm', '*.xbm', '*.xpm']) self.file_model.setNameFilterDisables(False) self.file_model.setRootPath(self.settings.get('Directory', 'default')) self.ui.treeView.setModel(self.file_model) self.ui.treeView.setColumnWidth(0, 120) self.ui.treeView.setColumnWidth(1, 120) self.ui.treeView.hideColumn(1) self.ui.treeView.hideColumn(2) # Double click self.ui.treeView.activated.connect(self.on_dir_list_activated) # Update file list self.ui.treeView.clicked.connect(self.on_dir_list_clicked) # Open parent self.ui.pushButton_open_parent.clicked.connect(self.on_open_parent) self.ui.pushButton_favorite.clicked.connect(self.on_manage_favorite) # Shortcuts _translate = QCoreApplication.translate self.ui.actionExit.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Exit'))) self.ui.actionOpen_next.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Next'))) self.ui.actionOpen_previous.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Previous'))) self.ui.actionChange_directory.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Directory'))) self.ui.actionAdd_to_favorites.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Add to favorites'))) self.ui.actionRemove_from_favorites.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Remove from favorites'))) self.ui.actionSlideshow.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Slideshow'))) self.ui.actionZoom_in.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Zoom in'))) self.ui.actionZoom_out.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Zoom out'))) self.ui.actionOriginal_size.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Zoom original'))) self.ui.actionRotate_clockwise.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Rotate clockwise'))) self.ui.actionRotate_counterclockwise.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Rotate counterclockwise'))) self.ui.actionFlip_horizontally.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Flip horizontal'))) self.ui.actionFlip_vertically.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Flip vertical'))) self.ui.actionFit_image_width.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Fit to width'))) self.ui.actionFit_image_height.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Fit to height'))) self.ui.actionFile_list.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Toggle filelist'))) self.ui.actionFullscreen.setShortcut(_translate("Hitagi", self.settings.get('Hotkeys', 'Fullscreen'))) # Load favorites in UI self.load_favorites() # Background self.ui.graphicsView.setBackgroundBrush(QBrush(QColor(self.settings.get('Look', 'background')), Qt.SolidPattern)) # Save current height for fullscreen mode self.default_menubar_height = self.ui.menubar.height() # Save current width for file list self.default_filelist_width = self.ui.fileWidget.width() def load_favorites(self): self.favorites = FavoritesModel() self.ui.menuFavorites.clear() for item in self.favorites.items(): self.ui.menuFavorites.addAction(item).triggered.connect((lambda item: lambda: self.on_open_favorite(item))(item)) def on_open_favorite(self, path): self.main_controller.change_directory(path) def center_ui(self): ui_geometry = self.frameGeometry() center_point = QDesktopWidget().availableGeometry().center() ui_geometry.moveCenter(center_point) self.move(ui_geometry.topLeft()) # Qt show event def showEvent(self, event): self.main_controller.start(self.arguments['image_path']) # Arguments and starting behaviour # Start in fullscreen mode according to settings if self.settings.get('Misc', 'fullscreen_mode') == 'True': self.on_fullscreen() # Initialize container geometry to canvas self.canvas_controller.update(self.ui.graphicsView.width(), self.ui.graphicsView.height()) self.main_controller.update_canvas() def update_resize_timer(self, interval=None): if self.resize_timer is not None: self.killTimer(self.resize_timer) if interval is not None: self.resize_timer = self.startTimer(interval) else: self.resize_timer = None # Qt resize event def resizeEvent(self, event): self.update_resize_timer(300) # Qt timer event def timerEvent(self, event): if event.timerId() == self.resize_timer: self.update_resize_timer() self.resizeCompleted.emit() def resize_completed(self): self.canvas_controller.update(self.ui.graphicsView.width(), self.ui.graphicsView.height()) self.main_controller.update_canvas() # Additional static shortcuts def keyPressEvent(self, e): if e.key() == Qt.Key_Escape and self.model.is_fullscreen: self.main_controller.toggle_fullscreen() def on_open_parent(self): parent_index = self.file_model.parent(self.file_model.index(self.file_model.rootPath())) self.file_model.setRootPath(self.file_model.filePath(parent_index)) self.ui.treeView.setRootIndex(parent_index) # Update directory path self.model.directory = self.file_model.filePath(parent_index) self.update_ui_from_model() def on_dir_list_activated(self, index): if self.file_model.isDir(index) is not False: self.file_model.setRootPath(self.file_model.filePath(index)) self.ui.treeView.setRootIndex(index) # Save current path self.model.directory = self.file_model.filePath(index) self.update_ui_from_model() def on_dir_list_clicked(self, index): self.main_controller.open_image(self.file_model.filePath(index)) # File menu def on_set_as_wallpaper(self): from hitagilib.view.WallpaperView import WallpaperDialog from hitagilib.controller.wallpaper import WallpaperController image = self.model.get_image() if image is not None: dialog = WallpaperDialog(self, None, WallpaperController(self.model), image) dialog.show() def on_clipboard(self): self.main_controller.copy_to_clipboard() def on_current_dir(self): if not self.main_controller.open_in_explorer(): self.show_explorer_error() def on_options(self): from hitagilib.view.OptionsView import OptionDialog self.dialog = OptionDialog(self) self.dialog.show() def on_close(self): if self.slideshow.isRunning(): self.slideshow.exit() self.close() # Folder menu def on_next_item(self): current_index = self.ui.treeView.currentIndex() # Slideshow restart - determine if we are at the end of our file list if self.slideshow.is_running and self.settings.get('Slideshow', 'restart') == 'True' and not self.ui.treeView.indexBelow(current_index).isValid(): self.main_controller.open_image(self.file_model.filePath(current_index)) self.on_slideshow_restart(0) # Restart slideshow elif self.slideshow.is_running and self.settings.get('Slideshow', 'random') == 'True': # Random index - moveCursor expects constants @http://doc.qt.io/qt-5/qabstractitemview.html#CursorAction-enum index = self.ui.treeView.moveCursor(randint(0,9), Qt.NoModifier) self.ui.treeView.setCurrentIndex(index) self.main_controller.open_image(self.file_model.filePath(index)) else: # Proceed normally, scroll down index = self.ui.treeView.moveCursor(QAbstractItemView.MoveDown, Qt.NoModifier) self.ui.treeView.setCurrentIndex(index) self.main_controller.open_image(self.file_model.filePath(index)) def on_previous_item(self): current_index = self.ui.treeView.currentIndex() # Slideshow restart (reverse) - determine if we are the the top of our file list if self.slideshow.is_running and self.settings.get('Slideshow', 'restart') == 'True' and not self.ui.treeView.indexAbove(current_index).isValid(): self.main_controller.open_image(self.file_model.filePath(current_index)) self.on_slideshow_restart(1) # Restart slideshow elif self.slideshow.is_running and self.settings.get('Slideshow', 'random') == 'True': # Random index index = self.ui.treeView.moveCursor(randint(0,9), Qt.NoModifier) self.ui.treeView.setCurrentIndex(index) self.main_controller.open_image(self.file_model.filePath(index)) else: # Proceed normally, scroll up index = self.ui.treeView.moveCursor(QAbstractItemView.MoveUp, Qt.NoModifier) self.ui.treeView.setCurrentIndex(index) self.main_controller.open_image(self.file_model.filePath(index)) def on_slideshow(self): if self.ui.actionSlideshow.isChecked(): self.slideshow.start() self.slideshow.is_running = True else: self.slideshow.is_running = False self.slideshow.exit() def on_slideshow_restart(self, direction): # 0: Restart from top to bottom # 1: Restart from bottom to top if direction == 0: index = self.ui.treeView.moveCursor(QAbstractItemView.MoveHome, Qt.NoModifier) self.main_controller.open_image(self.file_model.filePath(index)) else: index = self.ui.treeView.moveCursor(QAbstractItemView.MoveEnd, Qt.NoModifier) self.main_controller.open_image(self.file_model.filePath(index)) self.ui.treeView.setCurrentIndex(index) def on_change_directory(self): self.main_controller.change_directory() # View menu def on_zoom_in(self): self.canvas_controller.scale_image(1.1) def on_zoom_out(self): self.canvas_controller.scale_image(0.9) def on_rotate_clockwise(self): self.canvas_controller.rotate_image(90) def on_rotate_counterclockwise(self): self.canvas_controller.rotate_image(-90) def on_flip_horizontal(self): self.canvas_controller.flip_image(0) def on_flip_vertical(self): self.canvas_controller.flip_image(1) def on_scale_image_to_width(self): self.canvas_controller.update_image(1) def on_scale_image_to_height(self): self.canvas_controller.update_image(2) def on_zoom_original(self): self.canvas_controller.update_image(3) def on_toggle_filelist(self): if self.ui.fileWidget.isHidden(): self.ui.fileWidget.show() else: self.ui.fileWidget.hide() self.update_resize_timer(300) def on_fullscreen(self): self.main_controller.toggle_fullscreen() if self.model.is_fullscreen: self.showFullScreen() if self.settings.get('Misc', 'hide_menubar') == 'True': self.ui.menubar.setMaximumHeight(0) # Workaround to preserve shortcuts else: self.showNormal() if self.settings.get('Misc', 'hide_menubar') == 'True': self.ui.menubar.setMaximumHeight(self.default_menubar_height) self.canvas_controller.update(self.ui.graphicsView.width(), self.ui.graphicsView.height()) self.main_controller.update_canvas() # Favorite button def on_manage_favorite(self): if self.main_controller.check_favorites(self.model.directory): self.on_remove_from_favorites() else: self.on_add_to_favorites() # Favorite menu def on_add_to_favorites(self): self.main_controller.add_to_favorites() self.load_favorites() self.update_ui_from_model() def on_remove_from_favorites(self): self.main_controller.remove_from_favorites() self.load_favorites() self.update_ui_from_model() # Help menu def on_changelog(self): webbrowser.open('https://github.com/gimu/hitagi-reader/releases') def on_about(self): from hitagilib.view.AboutView import AboutDialog dialog = AboutDialog(self, None, None) dialog.show() def on_fileWidget_visibilityChanged(self, visible): """On file list hide/show and de/attachment""" if visible: self.ui.actionFile_list.setChecked(True) else: self.ui.actionFile_list.setChecked(False) self.update_resize_timer(300) def show_explorer_error(self): notify = QMessageBox() notify.setWindowTitle("Error") notify.setText(QCoreApplication.translate('Hitagi', "Couldn't open the current directory with an appropriate filemanager!")) notify.exec_() def update_ui_from_model(self): """Update UI from model.""" self.settings = SettingsModel() # On changing directory self.file_model.setRootPath(self.model.directory) self.ui.treeView.setRootIndex(self.file_model.index(self.model.directory)) # Update favorite button if self.main_controller.check_favorites(self.model.directory): self.ui.pushButton_favorite.setText(QCoreApplication.translate('Hitagi', "Unfavorite")) else: self.ui.pushButton_favorite.setText(QCoreApplication.translate('Hitagi', "Favorite")) # Canvas update self.ui.graphicsView.setScene(self.canvas.scene)
class Ui_MainWindow(object): def setupUi(self, MainWindow): MainWindow.setObjectName("MainWindow") MainWindow.resize(680, 482) self.centralWidget = QtWidgets.QWidget(MainWindow) self.centralWidget.setObjectName("centralWidget") self.frame = E(self.centralWidget) self.frame.setGeometry(QtCore.QRect(9, 9, 431, 411)) self.frame.setFrameShape(QtWidgets.QFrame.StyledPanel) self.frame.setFrameShadow(QtWidgets.QFrame.Raised) self.frame.setObjectName("frame") self.c = Communicate() self.c.spriteDrawMsg.connect(self.frame.spriteDrawController) self.c.rectDrawMsg.connect(self.frame.rectDrawController) self.c.circleDrawMsg.connect(self.frame.circleDrawController) self.tabWidget = QtWidgets.QTabWidget(self.centralWidget) self.tabWidget.setGeometry(QtCore.QRect(450, 10, 221, 411)) self.tabWidget.setObjectName("tabWidget") self.tab = QtWidgets.QWidget() self.tab.setObjectName("tab") self.tabWidget.addTab(self.tab, "") self.tab_2 = QtWidgets.QWidget() self.tab_2.setObjectName("tab_2") self.treeView = QtWidgets.QTreeView(self.tab_2) self.treeView.setGeometry(QtCore.QRect(0, 0, 221, 221)) self.treeView.setObjectName("treeView") ########################################### get selected sprite file path and send signal to frame def sendSpriteDrawMsg(item): index = self.treeView.currentIndex() p = self.model.filePath(index) self.c.spriteDrawMsg.emit(p, "sprite") self.treeView.doubleClicked.connect(sendSpriteDrawMsg) ################################################################################################## ########################################### send drawRect signal to frame def sendRectDrawMsg(item): # do needed things here self.c.spriteDrawMsg.emit("rect") # send a signal to sendRectDrawMsg here ########################################################################## ########################################### send drawCircle signal to frame def sendCircleDrawMsg(item): # do needed things here self.c.spriteDrawMsg.emit("circle") # send a signal to sendCircleDrawMsg here ############################################################################# self.model = QFileSystemModel() self.path = "." self.model.setRootPath(self.path) # self.filter = Iterable("*.png") # self.model.setNameFilters(self.filter) # self.model.removeColumn(1) # self.model.removeColumn(2) # self.model.removeColumn(3) # self.model.setFilter(QDir.AllDirs | QDir.NoDotAndDotDot | QDir.AllEntries) # # self.proxyModel = QSortFilterProxyModel() # self.proxyModel.setSourceModel(model) # self.proxyModel.removeColumn(1) # self.proxyModel.removeColumn(2) # self.proxyModel.removeColumn(3) self.treeView.setModel(self.model) self.treeView.setRootIndex(self.model.index(self.path)) self.treeView.expandAll() self.listView = QtWidgets.QListView(self.tab_2) self.listView.setGeometry(QtCore.QRect(0, 240, 221, 141)) self.listView.setObjectName("listView") self.line = QtWidgets.QFrame(self.tab_2) self.line.setGeometry(QtCore.QRect(30, 220, 151, 20)) self.line.setFrameShape(QtWidgets.QFrame.HLine) self.line.setFrameShadow(QtWidgets.QFrame.Sunken) self.line.setObjectName("line") self.tabWidget.addTab(self.tab_2, "") MainWindow.setCentralWidget(self.centralWidget) self.menuBar = QtWidgets.QMenuBar(MainWindow) self.menuBar.setGeometry(QtCore.QRect(0, 0, 680, 25)) self.menuBar.setObjectName("menuBar") self.menuChert_Engine = QtWidgets.QMenu(self.menuBar) self.menuChert_Engine.setObjectName("menuChert_Engine") MainWindow.setMenuBar(self.menuBar) self.mainToolBar = QtWidgets.QToolBar(MainWindow) self.mainToolBar.setObjectName("mainToolBar") MainWindow.addToolBar(QtCore.Qt.TopToolBarArea, self.mainToolBar) self.statusBar = QtWidgets.QStatusBar(MainWindow) self.statusBar.setObjectName("statusBar") MainWindow.setStatusBar(self.statusBar) self.menuBar.addAction(self.menuChert_Engine.menuAction()) self.retranslateUi(MainWindow) self.tabWidget.setCurrentIndex(1) QtCore.QMetaObject.connectSlotsByName(MainWindow) def retranslateUi(self, MainWindow): _translate = QtCore.QCoreApplication.translate MainWindow.setWindowTitle(_translate("MainWindow", "MainWindow")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab), _translate("MainWindow", "Tab 1")) self.tabWidget.setTabText(self.tabWidget.indexOf(self.tab_2), _translate("MainWindow", "Tab 2")) self.menuChert_Engine.setTitle(_translate("MainWindow", "Chert Engine"))
class Explorer(QDialog): def __init__( self, parent, window_title=_("Select resources"), subtitle=_("Select files and/or folders to include") ): super().__init__(parent) self.logger = logging.getLogger(__name__) self.setModal(True) self.setSizeGripEnabled(True) self.setWindowTitle(window_title) self.subtitle = subtitle self.file_set = set() self.config = Configuration() self.__init_ui__() self.filename_filter = FilenameFilter() # self.show() def __init_ui__(self): # layout vert = QVBoxLayout(self) vert.setContentsMargins(0, 0, 0, 0) resource_dir = self.config.cfg_resource_dir() p_top = QVBoxLayout() lb_subtitle = QLabel(self.subtitle) lb_subtitle.setContentsMargins(10, 10, 10, 0) p_top.addWidget(lb_subtitle) self.model = QFileSystemModel() self.model.setRootPath(resource_dir) self.view = QTreeView() self.view.setModel(self.model) self.view.setRootIndex(self.model.index(self.model.rootPath())) self.view.setAlternatingRowColors(True) self.view.setSelectionMode(QAbstractItemView.MultiSelection) self.view.selectionModel().selectionChanged.connect(self.selection_changed) self.view.collapsed.connect(self.item_collapsed) self.view.expanded.connect(self.item_expanded) p_top.addWidget(self.view) p_info = QHBoxLayout() lb_resource = QLabel(_("resource dir") + ": " + resource_dir) lb_resource.setContentsMargins(10, 0, 10, 0) self.lb_selection_count = QLabel(str(self.selected_file_count()) + " " + _("resources selected")) self.lb_selection_count.setContentsMargins(10, 0, 10, 0) p_info.addWidget(self.lb_selection_count) p_info.addStretch(1) p_info.addWidget(lb_resource) p_top.addLayout(p_info) p_bottom = QHBoxLayout() self.pb_deselect = QPushButton(_("Deselect all")) self.pb_deselect.clicked.connect(self.pb_deselect_clicked) self.pb_deselect.setEnabled(self.selected_file_count() > 0) p_bottom.addWidget(self.pb_deselect) p_bottom.addStretch(1) self.pb_ok = QPushButton(_("OK")) self.pb_ok.setAutoDefault(True) self.pb_ok.clicked.connect(self.accept) p_bottom.addWidget(self.pb_ok) pb_cancel = QPushButton(_("Cancel")) pb_cancel.clicked.connect(self.reject) p_bottom.addWidget(pb_cancel) vert.addLayout(p_top) vert.addLayout(p_bottom) self.setLayout(vert) self.resize(self.config.explorer_width(), self.config.explorer_height()) width = self.view.width() - 50 self.view.setColumnWidth(0, width / 2) self.view.setColumnWidth(1, width / 6) self.view.setColumnWidth(2, width / 6) self.view.setColumnWidth(3, width / 6) def __persist__(self): # persist properties of the explorer self.config.set_explorer_width(self.width()) self.config.set_explorer_height(self.height()) self.config.persist() def __compute_filenames__(self, item_selection): # item_selection: a QItemSelection # return corresponding absolute filenames as a set, including filenames in underlying folders s = set() for index in item_selection.indexes(): # we have an index for each column in the model if index.column() == 0: path = index.model().filePath(index) if os.path.isdir(path): for root, directories, filenames in os.walk(path): for filename in filenames: if self.filename_filter.accept(filename): s.add(os.path.join(root, filename)) elif os.path.isfile(path): s.add(path) else: self.logger.warn("isUnknownThing", path) return s def showEvent(self, QShowEvent): # self.pb_ok.setFocus() pass def set_filename_filter(self, filename_filter): # set the FilenameFilter self.filename_filter = filename_filter def selected_file_count(self): return len(self.file_set) def selected_file_set(self): return frozenset(self.file_set) def selection_changed(self, selected, deselected): # selected, deselected: PyQt5.QtCore.QItemSelection selected_filenames = self.__compute_filenames__(selected) self.file_set.update(selected_filenames) deselected_filenames = self.__compute_filenames__(deselected) self.file_set.difference_update(deselected_filenames) self.pb_deselect.setEnabled(self.selected_file_count() > 0) self.lb_selection_count.setText(str(self.selected_file_count()) + " " + _("resources selected")) def item_expanded(self, index): # index: a QModelIndex # show all child items selected/deselected in accordance with state of parent folder pass def item_collapsed(self, index): pass def pb_deselect_clicked(self): self.view.selectionModel().clear() def hideEvent(self, QHideEvent): self.__persist__()
class AbstractPathCompleter(AbstractCompleter): """Base class for PathCompleter and GlobCompleter """ mustBeLoaded = True # global object. Reused by all completers _fsModel = QFileSystemModel() _ERROR = 'error' _HEADER = 'currentDir' _STATUS = 'status' _DIRECTORY = 'directory' _FILE = 'file' def __init__(self, text): self._originalText = text self._dirs = [] self._files = [] self._error = None self._status = None """hlamer: my first approach is making self._model static member of class. But, sometimes it returns incorrect icons. I really can't understand when and why. When it is private member of instance, it seems it works """ self._model = None # can't construct in the construtor, must be constructed in GUI thread @staticmethod def _filterHidden(paths): """Remove hidden and ignored files from the list """ return [path for path in paths if not os.path.basename(path).startswith('.') and not core.fileFilter().regExp().match(path)] def _classifyRowIndex(self, row): """Get list item type and index by it's row """ if self._error: assert row == 0 return (self._ERROR, 0) if row == 0: return (self._HEADER, 0) row -= 1 if self._status: if row == 0: return (self._STATUS, 0) row -= 1 if row in range(len(self._dirs)): return (self._DIRECTORY, row) row -= len(self._dirs) if row in range(len(self._files)): return (self._FILE, row) assert False def _formatHeader(self, text): """Format current directory for show it in the list of completions """ return '<font style="background-color: %s; color: %s">%s</font>' % \ (QApplication.instance().palette().color(QPalette.Window).name(), QApplication.instance().palette().color(QPalette.WindowText).name(), htmlEscape(text)) def rowCount(self): """Row count in the list of completions """ if self._error: return 1 else: count = 1 # current directory if self._status: count += 1 count += len(self._dirs) count += len(self._files) return count def _iconForPath(self, path): """Get icon for file or directory path. Uses QFileSystemModel """ if self._model is None: self._model = QFileSystemModel() index = self._model.index(path) return self._model.data(index, Qt.DecorationRole) def text(self, row, column): """Item text in the list of completions """ rowType, index = self._classifyRowIndex(row) if rowType == self._ERROR: return '<font color=red>%s</font>' % htmlEscape(self._error) elif rowType == self._HEADER: return self._formatHeader(self._headerText()) elif rowType == self._STATUS: return '<i>%s</i>' % htmlEscape(self._status) elif rowType == self._DIRECTORY: return self._formatPath(self._dirs[index], True) elif rowType == self._FILE: return self._formatPath(self._files[index], False) def icon(self, row, column): """Item icon in the list of completions """ rowType, index = self._classifyRowIndex(row) if rowType == self._ERROR: return QApplication.instance().style().standardIcon(QStyle.SP_MessageBoxCritical) elif rowType == self._HEADER: return None elif rowType == self._STATUS: return None elif rowType == self._DIRECTORY: return self._iconForPath(self._dirs[index]) elif rowType == self._FILE: return self._iconForPath(self._files[index]) def isSelectable(self, row, column): rowType, index = self._classifyRowIndex(row) return rowType in (self._DIRECTORY, self._FILE) def getFullText(self, row): """User clicked a row. Get inline completion for this row """ row -= 1 # skip current directory if row in range(len(self._dirs)): return self._dirs[row] + '/' else: row -= len(self._dirs) # skip dirs if row in range(len(self._files)): return self._files[row] return None
class AssetBrowser(QMainWindow, Ui_MainWindow, PlaygroundModule): Name = "asset_browser" def __init__(self, module_manager): super(AssetBrowser, self).__init__() self.setupUi(self) self.init_module(module_manager) self.dir_model = QFileSystemModel() self.dir_model.setFilter(QDir.NoDotAndDotDot | QDir.AllDirs) self.dir_model.setReadOnly(False) self.dir_view.setModel(self.dir_model) self.dir_view.hideColumn(1) self.dir_view.hideColumn(2) self.dir_view.hideColumn(3) self.file_model = QFileSystemModel() self.file_model.setFilter(QDir.NoDotAndDotDot | QDir.Files) self.file_model.setReadOnly(False) self.file_view.setModel(self.file_model) self.dock = self.modules_manager.new_docked(self, self.Name, "Asset browser", Qt.BottomDockWidgetArea) self.modules_manager.main_window.splitDockWidget(self.dock, self.modules_manager["asset_view"].dock, Qt.Horizontal) def on_open_project(self, project): project_dir = project.project_dir path = os.path.join(project_dir) self.dir_model.setRootPath(path) self.file_model.setRootPath(path) self.dir_view.setRootIndex(self.dir_model.index(path)) self.file_view.setRootIndex(self.file_model.index(path)) def dir_clicked(self, idx): path = self.dir_model.fileInfo(idx).absoluteFilePath() self.file_view.setRootIndex(self.file_model.setRootPath(path)) def file_doubleclicked(self, idx): fileinfo = self.file_model.fileInfo(idx) path = fileinfo.absoluteFilePath() ext = fileinfo.suffix() asset_name = path.replace(self.project_manager.project_dir, '').replace('/src/', '').split('.')[0] self.modules_manager.open_asset(path, asset_name, ext) def file_clicked(self, idx): fileinfo = self.file_model.fileInfo(idx) path = fileinfo.absoluteFilePath() ext = fileinfo.suffix() asset_name = path.replace(self.project_manager.project_dir, '').replace('/src/', '').split('.')[0] self.modules_manager.show_asset(path, asset_name, ext)
parser.addPositionalArgument('directory', "The directory to start in.") parser.process(app) try: rootPath = parser.positionalArguments().pop(0) except IndexError: rootPath = None model = QFileSystemModel() model.setRootPath('') if parser.isSet(dontUseCustomDirectoryIconsOption): model.iconProvider().setOptions( QFileIconProvider.DontUseCustomDirectoryIcons) tree = QTreeView() tree.setModel(model) if rootPath is not None: rootIndex = model.index(QDir.cleanPath(rootPath)) if rootIndex.isValid(): tree.setRootIndex(rootIndex) # Demonstrating look and feel features. tree.setAnimated(False) tree.setIndentation(20) tree.setSortingEnabled(True) availableSize = QApplication.desktop().availableGeometry(tree).size() tree.resize(availableSize / 2) tree.setColumnWidth(0, tree.width() / 3) tree.setWindowTitle("Dir View") tree.show()
def load_project_structure2(self): model = QFileSystemModel() model.setRootPath(My_Sync.path2) self.treeView_2.setModel(model) self.treeView_2.setRootIndex(model.index(My_Sync.path2)) self.treeView_2.show()
class LocalPathView(QTreeView): def __init__ (self): super(LocalPathView, self).__init__() self._model = QFileSystemModel() self._model.setFilter(QDir.Dirs | QDir.Drives | QDir.NoDotAndDotDot | QDir.AllDirs) self._model.setRootPath('') self.setModel(self._model ) self.hideColumn(1); # removing Size Column self.hideColumn(2); # removing Type Column self.setAnimated(False) self.setSortingEnabled(True) self.header().setSortIndicator(0, Qt.AscendingOrder) width = self.size().width() >> 1 self.setColumnWidth(0, width*0.7) self.setColumnWidth(1, width*0.3) index = self._model.index(QDir.currentPath()) self.selectionModel().setCurrentIndex(index, QItemSelectionModel.Select | QItemSelectionModel.Rows) self.expand(index) self.scrollTo(index) @property def selectedDir(self): return self._model.filePath(self.selectionModel().selectedIndexes()[0])