本文整理汇总了Python中PyQt5.QtWidgets.QTreeView.selectionModel方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeView.selectionModel方法的具体用法?Python QTreeView.selectionModel怎么用?Python QTreeView.selectionModel使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTreeView
的用法示例。
在下文中一共展示了QTreeView.selectionModel方法的10个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: VisualStates
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [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)
示例2: FilenamePrompt
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
#.........这里部分代码省略.........
# 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')]
示例3: LeftSideBar
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
class LeftSideBar(QWidget):
treeViewSelectionChanged = pyqtSignal(QModelIndex, QModelIndex)
treeViewDoubleClicked = pyqtSignal(QModelIndex)
addPlaylistRequested = pyqtSignal()
removePlaylistRequested = pyqtSignal(UUID)
addToPlaylistRequested = pyqtSignal(UUID)
playlistAdded = pyqtSignal(UUID)
playlistRenamed = pyqtSignal(UUID, str)
def __init__(self, tree_items, parent=None):
super(LeftSideBar, self).__init__(parent)
self._tree_items = tree_items
self._restoreSettings()
self._setTreeView()
self._setAlbumCoverBox()
self._renderUI()
self.setMinimumWidth(FRONT_COVER_MIN_WIDTH)
self.setMaximumWidth(FRONT_COVER_MAX_WIDTH)
def _restoreSettings(self):
pass
def _setTreeView(self):
self.treeModel = TreeModel()
self.treeModel.addTopLevelItems(self._tree_items.keys())
self.leftBarView = QTreeView()
self.leftBarView.setModel(self.treeModel)
self.leftBarView.setHeaderHidden(True)
self.leftBarView.setRootIsDecorated(False)
self.leftBarView.setItemsExpandable(False)
self.leftBarView.setMouseTracking(True)
self.leftBarView.expandAll()
self.leftBarView.setFocusPolicy(Qt.NoFocus)
self.leftBarView.setSelectionBehavior(QAbstractItemView.SelectRows)
self.leftBarView.setSelectionMode(QAbstractItemView.SingleSelection)
self.leftBarView.setEditTriggers(QAbstractItemView.SelectedClicked)
self.leftBarView.selectionModel().currentRowChanged.connect(
lambda c, p: self.treeViewSelectionChanged.emit(c, p))
self.leftBarView.selectionModel().setCurrentIndex(
self.leftBarView.model().index(
0, 0, self.leftBarView.model().index(0, 0)),
QItemSelectionModel.Select)
self.leftBarView.doubleClicked.connect(
lambda i: self.treeViewDoubleClicked.emit(i))
delegate = LeftSideBarDelegate(self.leftBarView)
self.leftBarView.setItemDelegate(delegate)
delegate.addPlaylistRequested.connect(
lambda: self.addPlaylistRequested.emit())
delegate.removePlaylistRequested.connect(
lambda i: self.removePlaylistRequested.emit(
self.__getUuidFromIndex(i)))
delegate.addToPlaylistRequested.connect(
lambda i:
self.addToPlaylistRequested.emit(self.__getUuidFromIndex(i)))
delegate.editingFinished.connect(self._onRenamed)
def _onRenamed(self, index, text):
self.playlistRenamed.emit(
self.__getUuidFromIndex(index),
text)
@property
def model(self):
return self.treeModel
def _setAlbumCoverBox(self):
self.albumCoverBox = CoverArtBox()
def _renderUI(self):
self.layout = QVBoxLayout()
self.layout.setContentsMargins(0, 0, 0, 0)
self.layout.setSpacing(0)
self.layout.addWidget(self.leftBarView)
self.layout.addWidget(self.albumCoverBox)
self.setLayout(self.layout)
@QtCore.pyqtSlot(str, str, bytes)
def changeCoverArtBoxInformation(self, title, artist, cover):
self.albumCoverBox.setCoverArtBox(title, artist, cover)
@QtCore.pyqtSlot(UUID, str, int, int)
def addPlaylistEntry(self, uuid, name, row=0, column=0):
model = self.model
parent = model.getTopLevelIndex('PLAYLISTS')
if model.insertPlaylistEntry(row, name, uuid, parent):
self.playlistAdded.emit(uuid)
child = model.index(row, column, parent)
#.........这里部分代码省略.........
示例4: Widget
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
#.........这里部分代码省略.........
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())
# signals
self.searchEntry.returnPressed.connect(self.slotReturnPressed)
self.searchEntry.textChanged.connect(self.updateFilter)
self.treeView.doubleClicked.connect(self.slotDoubleClicked)
self.treeView.customContextMenuRequested.connect(self.showContextMenu)
self.treeView.selectionModel().currentChanged.connect(self.updateText)
self.treeView.model().dataChanged.connect(self.updateFilter)
# highlight text
self.highlighter = highlight.Highlighter(self.textView.document())
# complete on snippet variables
self.searchEntry.setCompleter(QCompleter([
':icon', ':indent', ':menu', ':name', ':python', ':selection',
':set', ':symbol', ':template', ':template-run'], self.searchEntry))
self.readSettings()
app.settingsChanged.connect(self.readSettings)
app.translateUI(self)
self.updateColumnSizes()
self.setAcceptDrops(True)
def dropEvent(self, ev):
if not ev.source() and ev.mimeData().hasUrls():
filename = ev.mimeData().urls()[0].toLocalFile()
if filename:
ev.accept()
from . import import_export
import_export.load(filename, self)
def dragEnterEvent(self, ev):
if not ev.source() and ev.mimeData().hasUrls():
ev.accept()
def translateUI(self):
try:
self.searchEntry.setPlaceholderText(_("Search..."))
except AttributeError:
pass # not in Qt 4.6
示例5: OpenedFileExplorer
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [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: OpenedFileExplorer
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [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):
#.........这里部分代码省略.........
示例7: QStandardItem
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
# Defining a couple of items
americaItem = QStandardItem("America")
canadaItem = QStandardItem("Canada")
europeItem = QStandardItem("Europe")
franceItem = QStandardItem("France")
brittanyItem = QStandardItem("Brittany")
# Building up the hierarchy
rootItem.appendRow(americaItem)
rootItem.appendRow(europeItem)
americaItem.appendRow(canadaItem)
europeItem.appendRow(franceItem)
franceItem.appendRow(brittanyItem)
tree_view.setModel(model)
# Bind selection to the print_selection function (must be after the model setup)
selection_model = tree_view.selectionModel()
selection_model.selectionChanged.connect(print_selection)
tree_view.expandAll() # expand all (this is not the case by default)
tree_view.show()
# The mainloop of the application. The event handling starts from this point.
# The exec_() method has an underscore. It is because the exec is a Python keyword. And thus, exec_() was used instead.
exit_code = app.exec_()
# The sys.exit() method ensures a clean exit.
# The environment will be informed, how the application ended.
sys.exit(exit_code)
示例8: Installed
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
class Installed(preferences.Group):
"""Overview of installed extensions.
A QTreeView lists the metadata of all installed extensions.
If the currently selected extension provides a configuration
widget it is displayed in the bottom group of the page.
With a checkbox individual extensions can be deactivated.
Metadata is listed for all *installed* extensions, regardless
of manual deactivation or load failure.
"""
def __init__(self, page):
super(Installed, self).__init__(page)
layout = QVBoxLayout()
self.setLayout(layout)
# This must be called before self.populate() because
# the data model relies on the labels
app.translateUI(self)
self.tree = QTreeView()
self.name_items = {}
self._selected_extension = ''
self.tree.setModel(QStandardItemModel())
self.tree.model().setColumnCount(2)
self.tree.setSelectionBehavior(QAbstractItemView.SelectRows)
self.tree.setEditTriggers(QAbstractItemView.NoEditTriggers)
self.tree.setHeaderHidden(True)
self.tree.header().setSectionResizeMode(
0, QHeaderView.ResizeToContents)
self.tree.selectionModel().selectionChanged.connect(
self.selection_changed)
self.populate()
layout.addWidget(self.tree)
def translateUI(self):
self.setTitle(_("Installed Extensions"))
self.config_labels = {
'extension-name': _("Name"),
'maintainers': _("Maintainer(s)"),
'version': _("Version"),
'api-version': _("API version"),
'license': _("License"),
'short-description': _("Short Description"),
'description': _("Description"),
'repository': _("Repository"),
'website': _("Website"),
'dependencies': _("Dependencies")
}
def loadSettings(self):
s = QSettings()
self.setEnabled(self.page().active())
s.beginGroup("extension-settings/installed")
inactive = s.value("inactive", [], list)
for ext in self.name_items.keys():
self.name_items[ext].setCheckState(
Qt.Checked if ext not in inactive else Qt.Unchecked)
self.tree.model().dataChanged.connect(self.page().changed)
def saveSettings(self):
s = QSettings()
s.beginGroup("extension-settings/installed")
inactive = [ext for ext in self.name_items.keys()
if self.name_items[ext].checkState() == Qt.Unchecked]
s.setValue("inactive", inactive)
def populate(self):
"""Populate the tree view with data from the installed extensions.
"""
# TODO/Question:
# Would it make sense to move this to a dedicated model class
# complementing the FailedModel?
root = self.tree.model().invisibleRootItem()
extensions = app.extensions()
for ext in extensions.installed_extensions():
ext_infos = extensions.infos(ext)
display_name = ext_infos.get(ext, ext) if ext_infos else ext.name()
loaded_extension = extensions.get(ext)
if loaded_extension:
display_name += ' ({})'.format(loaded_extension.load_time())
name_item = QStandardItem(display_name)
name_item.extension_name = ext
name_item.setCheckable(True)
self.name_items[ext] = name_item
icon = extensions.icon(ext)
if icon:
name_item.setIcon(icon)
root.appendRow([name_item])
for entry in [
'extension-name',
'short-description',
'description',
'version',
'api-version',
#.........这里部分代码省略.........
示例9: Explorer
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
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):
#.........这里部分代码省略.........
示例10: TapeWidget
# 需要导入模块: from PyQt5.QtWidgets import QTreeView [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeView import selectionModel [as 别名]
#.........这里部分代码省略.........
root_item = self._tape_model.invisibleRootItem()
if parent_index == None:
parent_item = root_item
else:
parent_item = self._tape_model.itemFromIndex(parent_index)
if note != None:
assert note not in self.notes()
else:
note = self.create_empty_note()
item = QStandardItem()
set_item_note(item, note)
parent_item.appendRow(item)
def add_and_focus_note(self, parent_proxy_index = None):
if parent_proxy_index != None:
parent_index = self._tape_filter_proxy_model.mapToSource(parent_proxy_index)
else:
parent_index = None
self.add_note(parent_index = parent_index)
if parent_proxy_index != None:
self._view.expand(parent_proxy_index)
parent_item = self._tape_model.itemFromIndex(parent_index)
else:
parent_item = self._tape_model.invisibleRootItem()
# NOTE: It's likely that the new note does not match the filter and won't not be present
# in the proxy model. We want to select it and focus on it so the filter must be cleared.
# And it must be cleared before taking the index in the proxy because changing the filter
# may change the set of notes present in the proxy and invalidate the index.
self.set_filter('')
new_note_index = parent_item.child(parent_item.rowCount() - 1).index()
new_note_proxy_index = self._tape_filter_proxy_model.mapFromSource(new_note_index)
self.clear_selection()
self.set_note_selection(new_note_proxy_index, True)
self._view.scrollTo(new_note_proxy_index)
def remove_notes(self, indexes):
remove_items(self._tape_model, indexes)
def clear(self):
self._tape_model.clear()
def set_filter(self, text):
# NOTE: This triggers textChanged() signal which applies the filter
self._search_box.setText(text)
def get_filter(self):
return self._search_box.text()
def selected_proxy_indexes(self):
return self._view.selectedIndexes()
def selected_indexes(self):
return [self._tape_filter_proxy_model.mapToSource(proxy_index) for proxy_index in self.selected_proxy_indexes()]
def set_note_selection(self, proxy_index, select):
assert proxy_index != None and proxy_index.isValid()
assert self._tape_model.itemFromIndex(self._tape_filter_proxy_model.mapToSource(proxy_index)) != None
self._view.selectionModel().select(
QItemSelection(proxy_index, proxy_index),
QItemSelectionModel.Select if select else QItemSelectionModel.Deselect
)
def clear_selection(self):
self._view.selectionModel().clear()
def delete_selected_notes(self):
self.remove_notes(self.selected_indexes())
def _new_sibling_handler(self):
selected_proxy_indexes = self._view.selectedIndexes()
if len(selected_proxy_indexes) > 1:
self.clear_selection()
selected_proxy_indexes = []
if len(selected_proxy_indexes) == 0 or selected_proxy_indexes[0].parent() == QModelIndex():
self.add_and_focus_note()
else:
self.add_and_focus_note(selected_proxy_indexes[0].parent())
def add_child_to_selected_element(self):
selected_proxy_indexes = self._view.selectedIndexes()
if len(selected_proxy_indexes) != 1:
return False
else:
self.add_and_focus_note(selected_proxy_indexes[0])
return True
def _new_child_handler(self):
added = self.add_child_to_selected_element()
if not added:
QMessageBox.warning(self, "Can't add note", "To be able to add a new child note select exactly one parent")