本文整理汇总了Python中PyQt5.QtWidgets.QTreeView.setCurrentIndex方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeView.setCurrentIndex方法的具体用法?Python QTreeView.setCurrentIndex怎么用?Python QTreeView.setCurrentIndex使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTreeView
的用法示例。
在下文中一共展示了QTreeView.setCurrentIndex方法的9个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: _mock_view_index
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
def _mock_view_index(model, category_idx, child_idx, qtbot):
"""Create a tree view from a model and set the current index.
Args:
model: model to create a fake view for.
category_idx: index of the category to select.
child_idx: index of the child item under that category to select.
"""
view = QTreeView()
qtbot.add_widget(view)
view.setModel(model)
idx = model.indexFromItem(model.item(category_idx).child(child_idx))
view.setCurrentIndex(idx)
return view
示例2: VisualStates
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
#.........这里部分代码省略.........
self.addDockWidget(Qt.LeftDockWidgetArea, dockWidget)
def createStateCanvas(self):
self.stateCanvas = QGraphicsView()
self.automataScene = AutomataScene()
self.automataScene.setSceneRect(0, 0, 2000, 2000)
self.automataScene.activeStateChanged.connect(self.activeStateChanged)
self.automataScene.stateInserted.connect(self.stateInserted)
self.automataScene.stateRemoved.connect(self.stateRemoved)
self.automataScene.transitionInserted.connect(self.transitionInserted)
self.automataScene.stateNameChangedSignal.connect(self.stateNameChanged)
self.automataScene.setActiveState(self.rootState)
self.setCentralWidget(self.stateCanvas)
self.stateCanvas.setScene(self.automataScene)
self.stateCanvas.setRenderHint(QPainter.Antialiasing)
self.stateCanvas.setAcceptDrops(True)
def stateInserted(self, state):
if self.activeState != self.rootState:
parent = self.treeModel.getByDataId(self.activeState.id)
self.treeModel.insertState(state, QColor(Qt.white), parent)
else:
self.treeModel.insertState(state, QColor(Qt.white))
def stateRemoved(self, state):
if self.activeState != self.rootState:
self.treeModel.removeState(state.stateData, self.activeState)
else:
self.treeModel.removeState(state.stateData)
def transitionInserted(self, tran):
# print('transition inserted:' + tran.transitionData.name)
pass
def stateNameChanged(self, state):
dataItem = self.treeModel.getByDataId(state.stateData.id)
if dataItem != None:
dataItem.name = state.stateData.name
self.treeModel.layoutChanged.emit()
def activeStateChanged(self):
if self.automataScene.activeState != self.activeState:
# print('visual states active state changed:' + self.automataScene.activeState.name)
self.activeState = self.automataScene.activeState
if self.activeState == self.rootState:
self.treeView.selectionModel().clearSelection()
else:
self.treeView.setCurrentIndex(self.treeModel.indexOf(self.treeModel.getByDataId(self.activeState.id)))
def upButtonClicked(self):
if self.activeState != None:
if self.activeState.parent != None:
# print('parent name:' + self.activeState.parent.name)
self.automataScene.setActiveState(self.activeState.parent)
def getStateById(self,state, id):
if state.id == id:
return state
else:
result = None
for child in state.getChildren():
result = self.getStateById(child, id)
if result is not None:
return result
return result
def treeItemClicked(self, index):
# print('clicked item.id:' + str(index.internalPointer().id))
state = self.getStateById(self.rootState, index.internalPointer().id)
if state is not None:
# set the active state as the loaded state
self.automataScene.setActiveState(state)
def timeStepDurationChanged(self, duration):
if self.activeState is not None:
self.activeState.setTimeStep(duration)
def variablesChanged(self, variables):
if self.activeState is not None:
self.activeState.setVariables(variables)
def functionsChanged(self, functions):
if self.activeState is not None:
self.activeState.setFunctions(functions)
def librariesChanged(self, libraries):
self.libraries = libraries
def configChanged(self):
if self.configDialog is not None:
self.config = self.configDialog.getConfig()
def getStateList(self, state, stateList):
if len(state.getChildren()) > 0:
stateList.append(state)
for s in state.getChildren():
self.getStateList(s, stateList)
示例3: FilenamePrompt
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
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:
#.........这里部分代码省略.........
示例4: AddBookmarkDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
class AddBookmarkDialog(QDialog, Ui_AddBookmarkDialog):
"""
Class implementing a dialog to add a bookmark or a bookmark folder.
"""
def __init__(self, parent=None, bookmarksManager=None):
"""
Constructor
@param parent reference to the parent widget (QWidget)
@param bookmarksManager reference to the bookmarks manager
object (BookmarksManager)
"""
super(AddBookmarkDialog, self).__init__(parent)
self.setupUi(self)
self.__bookmarksManager = bookmarksManager
self.__addedNode = None
self.__addFolder = False
if self.__bookmarksManager is None:
import Helpviewer.HelpWindow
self.__bookmarksManager = \
Helpviewer.HelpWindow.HelpWindow.bookmarksManager()
self.__proxyModel = AddBookmarkProxyModel(self)
model = self.__bookmarksManager.bookmarksModel()
self.__proxyModel.setSourceModel(model)
self.__treeView = QTreeView(self)
self.__treeView.setModel(self.__proxyModel)
self.__treeView.expandAll()
self.__treeView.header().setStretchLastSection(True)
self.__treeView.header().hide()
self.__treeView.setItemsExpandable(False)
self.__treeView.setRootIsDecorated(False)
self.__treeView.setIndentation(10)
self.__treeView.show()
self.locationCombo.setModel(self.__proxyModel)
self.locationCombo.setView(self.__treeView)
self.addressEdit.setInactiveText(self.tr("Url"))
self.nameEdit.setInactiveText(self.tr("Title"))
self.resize(self.sizeHint())
def setUrl(self, url):
"""
Public slot to set the URL of the new bookmark.
@param url URL of the bookmark (string)
"""
self.addressEdit.setText(url)
self.resize(self.sizeHint())
def url(self):
"""
Public method to get the URL of the bookmark.
@return URL of the bookmark (string)
"""
return self.addressEdit.text()
def setTitle(self, title):
"""
Public method to set the title of the new bookmark.
@param title title of the bookmark (string)
"""
self.nameEdit.setText(title)
def title(self):
"""
Public method to get the title of the bookmark.
@return title of the bookmark (string)
"""
return self.nameEdit.text()
def setDescription(self, description):
"""
Public method to set the description of the new bookmark.
@param description description of the bookamrk (string)
"""
self.descriptionEdit.setPlainText(description)
def description(self):
"""
Public method to get the description of the bookmark.
@return description of the bookamrk (string)
"""
return self.descriptionEdit.toPlainText()
def setCurrentIndex(self, idx):
"""
Public method to set the current index.
@param idx current index to be set (QModelIndex)
#.........这里部分代码省略.........
示例5: OpenedFileExplorer
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
class OpenedFileExplorer(DockWidget):
"""Opened File Explorer is list widget with list of opened files.
It implements switching current file, files sorting. Uses _OpenedFileModel internally.
Class instance created by Workspace.
"""
def __init__(self, workspace):
DockWidget.__init__(self, workspace, "&Opened Files", QIcon(":/enkiicons/filtered.png"), "Alt+O")
self._workspace = workspace
self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
self.tvFiles = QTreeView(self)
self.tvFiles.setHeaderHidden(True)
self.tvFiles.setEditTriggers(QAbstractItemView.SelectedClicked)
self.tvFiles.setContextMenuPolicy(Qt.CustomContextMenu)
self.tvFiles.setDragEnabled(True)
self.tvFiles.setDragDropMode(QAbstractItemView.InternalMove)
self.tvFiles.setRootIsDecorated(False)
self.tvFiles.setTextElideMode(Qt.ElideMiddle)
self.tvFiles.setUniformRowHeights(True)
self.tvFiles.customContextMenuRequested.connect(self._onTvFilesCustomContextMenuRequested)
self.setWidget(self.tvFiles)
self.setFocusProxy(self.tvFiles)
self.model = _OpenedFileModel(self) # Not protected, because used by Configurator
self.tvFiles.setModel(self.model)
self.tvFiles.setAttribute(Qt.WA_MacShowFocusRect, False)
self.tvFiles.setAttribute(Qt.WA_MacSmallSize)
self._workspace.currentDocumentChanged.connect(self._onCurrentDocumentChanged)
# disconnected by startModifyModel()
self.tvFiles.selectionModel().selectionChanged.connect(self._onSelectionModelSelectionChanged)
self.tvFiles.activated.connect(self._workspace.focusCurrentDocument)
core.actionManager().addAction("mView/aOpenedFiles", self.showAction())
def terminate(self):
"""Explicitly called destructor
"""
core.actionManager().removeAction("mView/aOpenedFiles")
def startModifyModel(self):
"""Blocks signals from model while it is modified by code
"""
self.tvFiles.selectionModel().selectionChanged.disconnect(self._onSelectionModelSelectionChanged)
def finishModifyModel(self):
"""Unblocks signals from model
"""
self.tvFiles.selectionModel().selectionChanged.connect(self._onSelectionModelSelectionChanged)
@pyqtSlot(Document, Document)
def _onCurrentDocumentChanged(self, oldDocument, currentDocument): # pylint: disable=W0613
""" Current document has been changed on workspace
"""
if currentDocument is not None:
index = self.model.documentIndex(currentDocument)
self.startModifyModel()
self.tvFiles.setCurrentIndex(index)
# scroll the view
self.tvFiles.scrollTo(index)
self.finishModifyModel()
@pyqtSlot(QItemSelection, QItemSelection)
def _onSelectionModelSelectionChanged(self, selected, deselected): # pylint: disable=W0613
""" Item selected in the list. Switch current document
"""
if not selected.indexes(): # empty list, last file closed
return
index = selected.indexes()[0]
# backup/restore current focused widget as setting active mdi window will steal it
focusWidget = self.window().focusWidget()
# set current document
document = self._workspace.sortedDocuments[index.row()]
self._workspace.setCurrentDocument(document)
# restore focus widget
if focusWidget:
focusWidget.setFocus()
@pyqtSlot(QPoint)
def _onTvFilesCustomContextMenuRequested(self, pos):
"""Connected automatically by uic
"""
menu = QMenu()
menu.addAction(core.actionManager().action("mFile/mClose/aCurrent"))
menu.addAction(core.actionManager().action("mFile/mSave/aCurrent"))
menu.addAction(core.actionManager().action("mFile/mReload/aCurrent"))
menu.addSeparator()
menu.addAction(core.actionManager().action("mFile/mFileSystem/aRename"))
#.........这里部分代码省略.........
示例6: Widget
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
class Widget(QWidget):
def __init__(self, panel):
super(Widget, self).__init__(panel)
layout = QVBoxLayout()
self.setLayout(layout)
layout.setSpacing(0)
self.searchEntry = SearchLineEdit()
self.treeView = QTreeView(contextMenuPolicy=Qt.CustomContextMenu)
self.textView = QTextBrowser()
applyButton = QToolButton(autoRaise=True)
editButton = QToolButton(autoRaise=True)
addButton = QToolButton(autoRaise=True)
self.menuButton = QPushButton(flat=True)
menu = QMenu(self.menuButton)
self.menuButton.setMenu(menu)
splitter = QSplitter(Qt.Vertical)
top = QHBoxLayout()
layout.addLayout(top)
splitter.addWidget(self.treeView)
splitter.addWidget(self.textView)
layout.addWidget(splitter)
splitter.setSizes([200, 100])
splitter.setCollapsible(0, False)
top.addWidget(self.searchEntry)
top.addWidget(applyButton)
top.addSpacing(10)
top.addWidget(addButton)
top.addWidget(editButton)
top.addWidget(self.menuButton)
# action generator for actions added to search entry
def act(slot, icon=None):
a = QAction(self, triggered=slot)
self.addAction(a)
a.setShortcutContext(Qt.WidgetWithChildrenShortcut)
icon and a.setIcon(icons.get(icon))
return a
# hide if ESC pressed in lineedit
a = act(self.slotEscapePressed)
a.setShortcut(QKeySequence(Qt.Key_Escape))
# import action
a = self.importAction = act(self.slotImport, 'document-open')
menu.addAction(a)
# export action
a = self.exportAction = act(self.slotExport, 'document-save-as')
menu.addAction(a)
# apply button
a = self.applyAction = act(self.slotApply, 'edit-paste')
applyButton.setDefaultAction(a)
menu.addSeparator()
menu.addAction(a)
# add button
a = self.addAction_ = act(self.slotAdd, 'list-add')
a.setShortcut(QKeySequence(Qt.Key_Insert))
addButton.setDefaultAction(a)
menu.addSeparator()
menu.addAction(a)
# edit button
a = self.editAction = act(self.slotEdit, 'document-edit')
a.setShortcut(QKeySequence(Qt.Key_F2))
editButton.setDefaultAction(a)
menu.addAction(a)
# set shortcut action
a = self.shortcutAction = act(self.slotShortcut, 'preferences-desktop-keyboard-shortcuts')
menu.addAction(a)
# delete action
a = self.deleteAction = act(self.slotDelete, 'list-remove')
a.setShortcut(QKeySequence(Qt.CTRL + Qt.Key_Delete))
menu.addAction(a)
# restore action
a = self.restoreAction = act(self.slotRestore)
menu.addSeparator()
menu.addAction(a)
# help button
a = self.helpAction = act(self.slotHelp, 'help-contents')
menu.addSeparator()
menu.addAction(a)
self.treeView.setSelectionBehavior(QTreeView.SelectRows)
self.treeView.setSelectionMode(QTreeView.ExtendedSelection)
self.treeView.setRootIsDecorated(False)
self.treeView.setAllColumnsShowFocus(True)
self.treeView.setModel(model.model())
self.treeView.setCurrentIndex(QModelIndex())
#.........这里部分代码省略.........
示例7: OpenedFileExplorer
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
class OpenedFileExplorer(DockWidget):
"""Opened File Explorer is list widget with list of opened files.
It implements switching current file, files sorting. Uses _OpenedFileModel internally.
Class instance created by Workspace.
"""
def __init__(self, workspace):
DockWidget.__init__(self, workspace, "&Opened Files", QIcon(":/enkiicons/filtered.png"), "Alt+O")
self._workspace = workspace
self.setAllowedAreas(Qt.LeftDockWidgetArea | Qt.RightDockWidgetArea)
self.tvFiles = QTreeView(self)
self.tvFiles.setHeaderHidden(True)
self.tvFiles.setEditTriggers(QAbstractItemView.SelectedClicked)
self.tvFiles.setContextMenuPolicy(Qt.CustomContextMenu)
self.tvFiles.setDragEnabled(True)
self.tvFiles.setDragDropMode(QAbstractItemView.InternalMove)
self.tvFiles.setRootIsDecorated(False)
self.tvFiles.setTextElideMode(Qt.ElideMiddle)
self.tvFiles.setUniformRowHeights(True)
self.tvFiles.customContextMenuRequested.connect(self._onTvFilesCustomContextMenuRequested)
self.setWidget(self.tvFiles)
self.setFocusProxy(self.tvFiles)
self.model = _OpenedFileModel(self) # Not protected, because used by Configurator
self.tvFiles.setModel(self.model)
self.tvFiles.setAttribute(Qt.WA_MacShowFocusRect, False)
self.tvFiles.setAttribute(Qt.WA_MacSmallSize)
self._workspace.currentDocumentChanged.connect(self._onCurrentDocumentChanged)
# disconnected by startModifyModel()
self.tvFiles.selectionModel().selectionChanged.connect(self._onSelectionModelSelectionChanged)
self.tvFiles.activated.connect(self._workspace.focusCurrentDocument)
core.actionManager().addAction("mView/aOpenedFiles", self.showAction())
# Add auto-hide capability.
self._waitForCtrlRelease = False
core.actionManager().action("mNavigation/aNext").triggered.connect(
self._setWaitForCtrlRelease)
core.actionManager().action("mNavigation/aPrevious").triggered.connect(
self._setWaitForCtrlRelease)
QApplication.instance().installEventFilter(self)
def terminate(self):
"""Explicitly called destructor
"""
core.actionManager().removeAction("mView/aOpenedFiles")
QApplication.instance().removeEventFilter(self)
def startModifyModel(self):
"""Blocks signals from model while it is modified by code
"""
self.tvFiles.selectionModel().selectionChanged.disconnect(self._onSelectionModelSelectionChanged)
def finishModifyModel(self):
"""Unblocks signals from model
"""
self.tvFiles.selectionModel().selectionChanged.connect(self._onSelectionModelSelectionChanged)
@pyqtSlot(Document, Document)
def _onCurrentDocumentChanged(self, oldDocument, currentDocument): # pylint: disable=W0613
""" Current document has been changed on workspace
"""
if currentDocument is not None:
index = self.model.documentIndex(currentDocument)
self.startModifyModel()
self.tvFiles.setCurrentIndex(index)
# scroll the view
self.tvFiles.scrollTo(index)
self.finishModifyModel()
@pyqtSlot(QItemSelection, QItemSelection)
def _onSelectionModelSelectionChanged(self, selected, deselected): # pylint: disable=W0613
""" Item selected in the list. Switch current document
"""
if not selected.indexes(): # empty list, last file closed
return
index = selected.indexes()[0]
# backup/restore current focused widget as setting active mdi window will steal it
focusWidget = self.window().focusWidget()
# set current document
document = self._workspace.sortedDocuments[index.row()]
self._workspace.setCurrentDocument(document)
# restore focus widget
if focusWidget:
focusWidget.setFocus()
@pyqtSlot(QPoint)
def _onTvFilesCustomContextMenuRequested(self, pos):
#.........这里部分代码省略.........
示例8: NavigatorDock
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
class NavigatorDock(DockWidget):
def __init__(self):
DockWidget.__init__(self, core.mainWindow(), '&Navigator', QIcon(':/enkiicons/goto.png'), "Alt+N")
self._tags = []
self._tree = QTreeView(self)
self._tree.installEventFilter(self)
self._tree.setHeaderHidden(True)
self.setFocusProxy(self._tree)
self._filterEdit = LineEdit(self)
self._filterEdit.setClearButtonVisible(True)
self._filterEdit.textEdited.connect(self._applyFilter)
self._filterEdit.clearButtonClicked.connect(self._applyFilter)
self._filterEdit.clearButtonClicked.connect(self._tree.setFocus)
self._filterEdit.clearButtonClicked.connect(self._hideFilter)
self._filterEdit.installEventFilter(self)
self._displayWidget = QWidget(self)
layout = QVBoxLayout(self._displayWidget)
layout.addWidget(self._tree)
layout.addWidget(self._filterEdit)
layout.setContentsMargins(0, 0, 0, 0)
self.setWidget(self._displayWidget)
self._tagModel = _TagModel(self._tree)
self._tagModel.jumpToTagDone.connect(self._hideFilter)
self._tree.setModel(self._tagModel)
self._tree.activated.connect(self._tagModel.onActivated)
self._tree.clicked.connect(self._tagModel.onActivated)
self._tagModel.modelAboutToBeReset.connect(self._onModelAboutToBeReset)
self._tagModel.modelReset.connect(self._onModelReset)
self._currentTagPath = None
self._errorLabel = None
self._installed = False
def term(self):
self._tagModel.term()
def install(self):
if not self._installed:
core.mainWindow().addDockWidget(Qt.RightDockWidgetArea, self)
core.actionManager().addAction("mView/aNavigator", self.showAction())
self._installed = True
def remove(self):
if self._installed:
core.mainWindow().removeDockWidget(self)
core.actionManager().removeAction("mView/aNavigator")
self.hide()
self._installed = False
def setTags(self, tags):
self._tags = tags
self._setFilteredTags(tags)
self._hideFilter()
if self.widget() is not self._displayWidget:
self.setWidget(self._displayWidget)
self._displayWidget.show()
if self._errorLabel is not None:
self._errorLabel.hide()
def _setFilteredTags(self, tags):
self._tagModel.setTags(tags)
def onError(self, error):
self._displayWidget.hide()
if self._errorLabel is None:
self._errorLabel = QLabel(self)
self._errorLabel.setWordWrap(True)
self._errorLabel.setText(error)
if not self.widget() is self._errorLabel:
self.setWidget(self._errorLabel)
self._errorLabel.show()
self._displayWidget.hide()
def _onModelAboutToBeReset(self):
currIndex = self._tree.currentIndex()
self._currentTagPath = self._tagModel.tagPathForIndex(currIndex) if currIndex.isValid() else None
def _onModelReset(self):
self._tree.expandAll()
# restore current item
if self._currentTagPath is not None:
index = self._tagModel.indexForTagPath(self._currentTagPath)
if index.isValid():
self._tree.setCurrentIndex(index)
def eventFilter(self, object_, event):
if object_ is self._tree:
#.........这里部分代码省略.........
示例9: _LocatorDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import setCurrentIndex [as 别名]
#.........这里部分代码省略.........
"""Set 'Loading...' message
"""
self._applyCompleter(None, StatusCompleter('<i>Loading...</i>'))
def onCompleterLoaded(self, command, completer):
"""The method called from _CompleterLoaderThread when the completer is ready
This code works in the GUI thread
"""
self._applyCompleter(command, completer)
def _applyCompleter(self, command, completer):
"""Apply completer. Called by _updateCompletion or by thread function when Completer is constructed
"""
self._loadingTimer.stop()
if command is not None:
command.onCompleterLoaded(completer)
if completer is None:
completer = _HelpCompleter([command])
if self._edit.cursorPosition() == len(self._edit.text()): # if cursor at the end of text
self._edit.setInlineCompletion(completer.inline())
self._model.setCompleter(completer)
if completer.columnCount() > 1:
self._table.resizeColumnToContents(0)
self._table.setColumnWidth(0, self._table.columnWidth(0) + 20) # 20 px spacing between columns
selItem = completer.autoSelectItem()
if selItem:
index = self._model.createIndex(selItem[0],
selItem[1])
self._table.setCurrentIndex(index)
def _onItemClicked(self, index):
"""Item in the TreeView has been clicked.
Open file, if user selected it
"""
if self._command is not None:
fullText = self._model.completer.getFullText(index.row())
if fullText is not None:
self._command.onItemClicked(fullText)
if self._tryExecCurrentCommand():
self.accept()
return
else:
self._edit.setText(self._command.lineEditText())
self._updateCurrentCommand()
self._edit.setFocus()
def _onEnterPressed(self):
"""User pressed Enter or clicked item. Execute command, if possible
"""
if self._table.currentIndex().isValid():
self._onItemClicked(self._table.currentIndex())
else:
self._tryExecCurrentCommand()
def _tryExecCurrentCommand(self):
if self._command is not None and self._command.isReadyToExecute():
self._command.execute()
self.accept()
return True
else: