本文整理汇总了Python中PyQt5.QtWidgets.QTreeWidget.takeTopLevelItem方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeWidget.takeTopLevelItem方法的具体用法?Python QTreeWidget.takeTopLevelItem怎么用?Python QTreeWidget.takeTopLevelItem使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTreeWidget
的用法示例。
在下文中一共展示了QTreeWidget.takeTopLevelItem方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ChangedDocumentsListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
#.........这里部分代码省略.........
diritem.setExpanded(True)
diritem.setFlags(Qt.ItemIsEnabled)
diritem.setIcon(0, icons.get('folder-open'))
for filename, document in sorted(dirs[dirname],
key=lambda item: util.naturalsort(item[0])):
fileitem = QTreeWidgetItem()
diritem.addChild(fileitem)
if documentwatcher.DocumentWatcher.instance(document).isdeleted():
itemtext = _("[deleted]")
icon = "dialog-error"
else:
itemtext = _("[modified]")
icon = "document-edit"
fileitem.setIcon(0, icons.get(icon))
fileitem.setText(0, filename)
fileitem.setText(1, itemtext)
fileitem.doc = document
# select the item if there is only one
if len(dirs) == 1 and len(list(dirs.values())[0]) == 1:
fileitem.setSelected(True)
self.tree.resizeColumnToContents(0)
self.tree.resizeColumnToContents(1)
self.updateButtons()
def removeDocument(self, document):
"""Remove the specified document from our list."""
for d in range(self.tree.topLevelItemCount()):
diritem = self.tree.topLevelItem(d)
for f in range(diritem.childCount()):
if diritem.child(f).doc is document:
i = diritem.takeChild(f)
i.doc = None
if diritem.childCount() == 0:
self.tree.takeTopLevelItem(d)
break
else:
continue
break
self.updateButtons()
# hide if no documents are left
if self.tree.topLevelItemCount() == 0:
self.hide()
def selectedDocuments(self):
"""Return the selected documents."""
return [i.doc for i in self.tree.selectedItems()]
def allDocuments(self):
"""Return all shown documents."""
return [self.tree.topLevelItem(d).child(f).doc
for d in range(self.tree.topLevelItemCount())
for f in range(self.tree.topLevelItem(d).childCount())]
def updateButtons(self):
"""Updates the buttons regarding the selection."""
docs_sel = self.selectedDocuments()
docs_all = self.allDocuments()
all_deleted_sel = all(documentwatcher.DocumentWatcher.instance(d).isdeleted()
for d in docs_sel)
all_deleted_all = all(documentwatcher.DocumentWatcher.instance(d).isdeleted()
for d in docs_all)
self.buttonSave.setEnabled(len(docs_sel) > 0)
self.buttonSaveAll.setEnabled(len(docs_all) > 0)
self.buttonReload.setEnabled(not all_deleted_sel)
self.buttonReloadAll.setEnabled(not all_deleted_all)
self.buttonShowDiff.setEnabled(len(docs_sel) == 1 and not all_deleted_sel)
示例2: MiscTab
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
class MiscTab(QWidget):
def __init__(self, parent=None):
super().__init__(parent)
self.name = self.tr("Misc")
self.markColorLabel = QLabel(self.tr("Default flag colors:"), self)
# TODO: enforce duplicate names avoidance
self.markColorWidget = QTreeWidget(self)
self.markColorWidget.setHeaderLabels(
(self.tr("Color"), self.tr("Name")))
self.markColorWidget.setRootIsDecorated(False)
self.markColorWidget.setSelectionBehavior(
QAbstractItemView.SelectRows)
# TODO: make this work correctly, top-level items only
# self.markColorWidget.setDragDropMode(QAbstractItemView.InternalMove)
self.addItemButton = QPushButton("+", self)
self.addItemButton.clicked.connect(self.addItem)
self.removeItemButton = QPushButton("−", self)
self.removeItemButton.clicked.connect(self.removeItem)
self.loadRecentFileBox = QCheckBox(
self.tr("Load most recent file on start"), self)
layout = QGridLayout(self)
l = 0
layout.addWidget(self.markColorLabel, l, 0, 1, 3)
l += 1
layout.addWidget(self.markColorWidget, l, 0, 1, 3)
l += 1
layout.addWidget(self.addItemButton, l, 0)
layout.addWidget(self.removeItemButton, l, 1)
l += 1
layout.addWidget(self.loadRecentFileBox, l, 0, 1, 3)
self.setLayout(layout)
self.readSettings()
def addItem(self):
def mangleNewName():
name = self.tr("New")
index = 0
while self.markColorWidget.findItems(name, Qt.MatchExactly, 1):
index += 1
name = "{0} ({1})".format(name, index)
return name
# TODO: not DRY with ctor
item = QTreeWidgetItem(self.markColorWidget)
item.setFlags(item.flags() | Qt.ItemIsEditable)
widget = ColorVignette(self)
widget.setColor(QColor(Qt.white))
widget.setMargins(2, 2, 2, 2)
widget.setMayClearColor(False)
self.markColorWidget.setItemWidget(item, 0, widget)
item.setText(1, mangleNewName())
self.markColorWidget.setCurrentItem(item)
self.markColorWidget.editItem(item, 1)
self.removeItemButton.setEnabled(True)
def removeItem(self):
i = self.markColorWidget.selectionModel().currentIndex().row()
self.markColorWidget.takeTopLevelItem(i)
if not self.markColorWidget.topLevelItemCount():
self.removeItemButton.setEnabled(False)
def readSettings(self):
entries = settings.readMarkColors()
for name, color in entries.items():
item = QTreeWidgetItem(self.markColorWidget)
item.setFlags(item.flags() | Qt.ItemIsEditable)
widget = ColorVignette(self)
widget.setColor(color)
widget.setMargins(2, 2, 2, 2)
widget.setMayClearColor(False)
self.markColorWidget.setItemWidget(item, 0, widget)
item.setText(1, name)
if not len(entries):
self.removeItemButton.setEnabled(False)
loadRecentFile = settings.loadRecentFile()
self.loadRecentFileBox.setChecked(loadRecentFile)
def writeSettings(self):
markColors = OrderedDict()
for i in range(self.markColorWidget.topLevelItemCount()):
item = self.markColorWidget.topLevelItem(i)
name = item.text(1)
color = self.markColorWidget.itemWidget(item, 0).color()
markColors[name] = color
settings.writeMarkColors(markColors)
loadRecentFile = self.loadRecentFileBox.isChecked()
settings.setLoadRecentFile(loadRecentFile)
示例3: PugdebugExpressionViewer
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
class PugdebugExpressionViewer(QWidget):
expression_added_signal = pyqtSignal(int, str)
expression_changed_signal = pyqtSignal(int, str)
def __init__(self):
super(PugdebugExpressionViewer, self).__init__()
# Action for adding a new expression
self.add_action = QAction(QIcon.fromTheme('list-add'), "&Add", self)
self.add_action.triggered.connect(self.handle_add_action)
# Action for deleting selected expressions
self.delete_action = QAction(
QIcon.fromTheme('list-remove'),
"&Delete", self
)
self.delete_action.setShortcut(QKeySequence("Del"))
self.delete_action.triggered.connect(self.handle_delete_action)
self.toolbar = QToolBar()
self.toolbar.setIconSize(QSize(16, 16))
self.toolbar.addAction(self.add_action)
self.toolbar.addAction(self.delete_action)
self.tree = QTreeWidget()
self.tree.setColumnCount(3)
self.tree.setHeaderLabels(['Expression', 'Type', 'Value'])
self.tree.setSelectionMode(QAbstractItemView.ContiguousSelection)
self.tree.setContextMenuPolicy(Qt.CustomContextMenu)
self.tree.customContextMenuRequested.connect(self.show_context_menu)
layout = QVBoxLayout()
layout.addWidget(self.toolbar)
layout.addWidget(self.tree)
self.setLayout(layout)
self.restore_state()
self.tree.itemChanged.connect(self.handle_item_changed)
def show_context_menu(self, point):
# Create the context menu on the tree widget
context_menu = QMenu(self)
# Add action is always visible
context_menu.addAction(self.add_action)
# If clicked on an row, offer to delete it
if self.tree.itemAt(point):
context_menu.addAction(self.delete_action)
point = self.tree.mapToGlobal(point)
context_menu.popup(point)
def add_expression(self, expression):
item = QTreeWidgetItem([expression, '', ''])
item.setFlags(
Qt.ItemIsEnabled |
Qt.ItemIsEditable |
Qt.ItemIsSelectable
)
self.tree.addTopLevelItem(item)
# Emit the signal to evaluate the expression
index = self.tree.indexOfTopLevelItem(item)
self.expression_added_signal.emit(index, expression)
def delete_selected(self):
"""Deletes currently selected items from the tree"""
for item in self.tree.selectedItems():
index = self.tree.indexOfTopLevelItem(item)
self.delete_expression(item)
self.select_next(index)
def select_next(self, index):
"""Selects the next item after an item has been deleted"""
prev_item = self.tree.topLevelItem(index - 1)
next_item = self.tree.topLevelItem(index)
if prev_item:
prev_item.setSelected(True)
elif next_item:
next_item.setSelected(True)
def clear_values(self):
"""Deletes values for all expressions"""
count = self.tree.topLevelItemCount()
for index in range(0, count):
item = self.tree.topLevelItem(index)
item.setData(1, Qt.DisplayRole, '')
item.setData(2, Qt.DisplayRole, '')
item.takeChildren()
def delete_expression(self, item):
"""Deletes the given item from the tree"""
index = self.tree.indexOfTopLevelItem(item)
self.tree.takeTopLevelItem(index)
def get_expressions(self):
#.........这里部分代码省略.........
示例4: SessionsManager
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
#.........这里部分代码省略.........
btn_layout.addWidget(btn_activate)
btn_layout.addWidget(btn_update)
btn_layout.addWidget(btn_delete)
btn_layout.addStretch()
btn_layout.addWidget(btn_details)
# Add widgets and layouts to the main layout
main_layout.addLayout(main_hbox)
main_hbox.addLayout(session_layout)
main_hbox.addWidget(line_frame)
main_hbox.addLayout(btn_layout)
main_hbox.setSizeConstraint(QLayout.SetFixedSize)
btn_details.toggled[bool].connect(content_frame.setVisible)
# Connections
self._session_list.itemSelectionChanged.connect(
self.load_session_content)
btn_activate.clicked.connect(self.open_session)
btn_update.clicked.connect(self.save_session)
btn_create.clicked.connect(self.create_session)
btn_delete.clicked.connect(self.delete_session)
def __load_sessions(self):
for session_name in self._manager.sessions:
item = QTreeWidgetItem()
item.setText(0, session_name)
item.setText(1, "FIXME: manage this!")
self._session_list.addTopLevelItem(item)
self._session_list.setCurrentItem(
self._session_list.topLevelItem(0))
def load_session_content(self):
"""Load the selected session, replacing the current session."""
item = self._session_list.currentItem()
self._content_list.clear()
if item is not None:
key = item.text(0)
files, projects = self._manager.get_session(key)
files_parent = QTreeWidgetItem(
self._content_list, [translations.TR_FILES])
for ffile in files:
QTreeWidgetItem(files_parent, [ffile[0]])
projects_parent = QTreeWidgetItem(
self._content_list, [translations.TR_PROJECT])
for project in projects:
QTreeWidgetItem(projects_parent, [project])
files_parent.setExpanded(True)
projects_parent.setExpanded(True)
def create_session(self):
"""Create a new Session."""
session_info = QInputDialog.getText(
None, translations.TR_SESSIONS_CREATE_TITLE,
translations.TR_SESSIONS_CREATE_BODY)
if session_info[1]:
session_name = session_info[0]
if not session_name or session_name in settings.SESSIONS:
QMessageBox.information(
self,
translations.TR_SESSIONS_MESSAGE_TITLE,
translations.TR_SESSIONS_MESSAGE_BODY)
return
self._manager.save_session_data(session_name)
self.close()
def save_session(self):
"""Save current session"""
if self._session_list.currentItem():
session_name = self._session_list.currentItem().text(0)
self._manager.save_session_data(session_name)
self._ninja.show_message(
translations.TR_SESSIONS_UPDATED_NOTIF.format(session_name))
self.load_session_content()
def open_session(self):
"""Open a saved session"""
if self._session_list.currentItem():
session_name = self._session_list.currentItem().text(0)
self._manager.load_session(session_name)
self._manager.set_current_session(session_name)
self.close()
def delete_session(self):
"""Delete a session"""
if self._session_list.currentItem():
key = self._session_list.currentItem().text(0)
self._manager.delete_session(key)
self._session_list.takeTopLevelItem(
self._session_list.currentIndex().row())
@property
def current_session(self):
return self._manager.current_session()
def showEvent(self, event):
super().showEvent(event)
self.__load_sessions()
def hideEvent(self, event):
super().hideEvent(event)
self._session_list.clear()
示例5: AddToProject
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
class AddToProject(QDialog):
def __init__(self, pathProjects, parent=None):
#pathProjects must be a list
super(AddToProject, self).__init__(parent)
self.setWindowTitle(_translate("AddToProject", "Add File to Project"))
self.pathSelected = ''
vbox = QVBoxLayout(self)
self._tree = QTreeWidget()
self._tree.header().setHidden(True)
self._tree.setSelectionMode(QTreeWidget.SingleSelection)
self._tree.setAnimated(True)
vbox.addWidget(self._tree)
hbox = QHBoxLayout()
btnAdd = QPushButton(_translate("AddToProject", "Add here!"))
btnCancel = QPushButton(_translate("AddToProject", "Cancel"))
hbox.addWidget(btnCancel)
hbox.addWidget(btnAdd)
vbox.addLayout(hbox)
#load folders
self._root = None
self._loading_items = {}
self.loading_projects(pathProjects)
self._thread_execution = ThreadExecution(
self._thread_load_projects, args=[pathProjects])
self._thread_execution.finished.connect(self._callback_load_project)
self._thread_execution.start()
btnCancel.clicked['bool'].connect(self.close)
btnAdd.clicked['bool'].connect(self._select_path)
def loading_projects(self, projects):
for project in projects:
loadingItem = LoadingItem()
item = loadingItem.add_item_to_tree(project, self._tree,
parent=self)
self._loading_items[project] = item
def _thread_load_projects(self, projects):
structures = []
for pathProject in projects:
folderStructure = file_manager.open_project(pathProject)
structures.append((folderStructure, pathProject))
self._thread_execution.storage_values = structures
def _callback_load_project(self):
structures = self._thread_execution.storage_values
if structures:
for structure, path in structures:
item = self._loading_items.pop(path, None)
if item is not None:
index = self._tree.indexOfTopLevelItem(item)
self._tree.takeTopLevelItem(index)
self._load_project(structure, path)
def _select_path(self):
item = self._tree.currentItem()
if item:
self.pathSelected = item.toolTip(0)
self.close()
def _load_project(self, folderStructure, folder):
if not folder:
return
name = file_manager.get_basename(folder)
item = QTreeWidgetItem(self._tree)
item.setText(0, name)
item.setToolTip(0, folder)
item.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
if folderStructure[folder][1] is not None:
folderStructure[folder][1].sort()
self._load_folder(folderStructure, folder, item)
item.setExpanded(True)
self._root = item
def _load_folder(self, folderStructure, folder, parentItem):
items = folderStructure[folder]
if items[1] is not None:
items[1].sort()
for _file in items[1]:
if _file.startswith('.'):
continue
subfolder = QTreeWidgetItem(parentItem)
subfolder.setText(0, _file)
subfolder.setToolTip(0, os.path.join(folder, _file))
subfolder.setIcon(0, QIcon(resources.IMAGES['tree-folder']))
self._load_folder(folderStructure,
os.path.join(folder, _file), subfolder)
示例6: EditorConfiguration
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
#.........这里部分代码省略.........
self._checkEndOfLine.setChecked(settings.USE_PLATFORM_END_OF_LINE)
vboxg6.addWidget(self._checkEndOfLine)
self._checkEndAtLastLine = QCheckBox(
translations.TR_PREFERENCES_EDITOR_CONFIG_END_AT_LAST_LINE)
self._checkEndAtLastLine.setChecked(settings.END_AT_LAST_LINE)
vboxg6.addWidget(self._checkEndAtLastLine)
self._checkTrailing = QCheckBox(
translations.TR_PREFERENCES_EDITOR_CONFIG_REMOVE_TRAILING)
self._checkTrailing.setChecked(settings.REMOVE_TRAILING_SPACES)
vboxg6.addWidget(self._checkTrailing)
self._allowWordWrap = QCheckBox(
translations.TR_PREFERENCES_EDITOR_CONFIG_WORD_WRAP)
self._allowWordWrap.setChecked(settings.ALLOW_WORD_WRAP)
vboxg6.addWidget(self._allowWordWrap)
formFeatures.addWidget(group6, 3, 1)
# pack all the groups
vbox.addWidget(container_widget_with_all_preferences)
vbox.addItem(QSpacerItem(0, 10, QSizePolicy.Expanding,
QSizePolicy.Expanding))
self._preferences.savePreferences.connect(self.save)
def _add_code_pep8(self):
item = QTreeWidgetItem()
item.setFlags(item.flags() | Qt.ItemIsEditable)
self._listIgnoreViolations.addTopLevelItem(item)
self._listIgnoreViolations.setCurrentItem(item)
self._listIgnoreViolations.editItem(item, 0)
def _remove_code_pep8(self):
index = self._listIgnoreViolations.indexOfTopLevelItem(
self._listIgnoreViolations.currentItem())
self._listIgnoreViolations.takeTopLevelItem(index)
def _enable_check_inline(self, val):
"""Method that takes a value to enable the inline style checking"""
if val == Qt.Checked:
self._checkStyle.setChecked(True)
def _enable_errors_inline(self, val):
"""Method that takes a value to enable the inline errors checking"""
if val == Qt.Checked:
self._checkErrors.setChecked(True)
def _disable_check_style(self, val):
"""Method that takes a value to disable the inline style checking"""
if val == Qt.Unchecked:
self._checkStyleOnLine.setChecked(False)
def _disable_show_errors(self, val):
"""Method that takes a value to disable the inline errors checking"""
if val == Qt.Unchecked:
self._showErrorsOnLine.setChecked(False)
def save(self):
"""Method to save settings"""
qsettings = IDE.ninja_settings()
settings.USE_TABS = bool(self._checkUseTabs.currentIndex())
qsettings.setValue('preferences/editor/useTabs',
settings.USE_TABS)
margin_line = self._spinMargin.value()
settings.MARGIN_LINE = margin_line
settings.pycodestylemod_update_margin_line_length(margin_line)
qsettings.setValue('preferences/editor/marginLine', margin_line)
settings.SHOW_MARGIN_LINE = self._checkShowMargin.isChecked()
示例7: CueListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
class CueListDialog(QDialog):
def __init__(self, **kwargs):
super().__init__(**kwargs)
self.setMinimumSize(400, 300)
self._cues = []
self.list = QTreeWidget(self)
self.list.setSelectionMode(self.list.SingleSelection)
self.list.setSelectionBehavior(self.list.SelectRows)
self.list.setAlternatingRowColors(True)
self.list.setIndentation(0)
self.list.setHeaderLabels(['Index', 'Name'])
self.list.header().setSectionResizeMode(QHeaderView.Fixed)
self.list.header().setSectionResizeMode(1, QHeaderView.Stretch)
self.list.header().setStretchLastSection(False)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.list)
self.buttons = QDialogButtonBox(self)
self.buttons.addButton(QDialogButtonBox.Cancel)
self.buttons.addButton(QDialogButtonBox.Ok)
self.layout().addWidget(self.buttons)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
def add_cue(self, cue):
try:
item = QTreeWidgetItem()
item.setTextAlignment(0, Qt.AlignCenter)
for n, prop in enumerate(['index', 'name']):
item.setText(n, str(cue.properties().get(prop, 'Undefined')))
self._cues.append(cue)
self.list.addTopLevelItem(item)
except Exception:
pass
def add_cues(self, cues):
for cue in cues:
self.add_cue(cue)
def remove_cue(self, index):
self.list.takeTopLevelItem(index)
return self._cues.pop(index)
def reset(self):
self.list.clear()
self._cues.clear()
def selected_cues(self):
cues = []
for item in self.list.selectedItems():
index = self.list.indexOfTopLevelItem(item)
cues.append(self._cues[index])
return cues
示例8: CueListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import takeTopLevelItem [as 别名]
class CueListDialog(QDialog):
def __init__(self, cues=None, properties=('index', 'name'), **kwargs):
super().__init__(**kwargs)
self.setMinimumSize(600, 400)
self._properties = list(properties)
self._cues = {}
self.list = QTreeWidget(self)
self.list.setSelectionMode(QTreeWidget.SingleSelection)
self.list.setSelectionBehavior(QTreeWidget.SelectRows)
self.list.setAlternatingRowColors(True)
self.list.setIndentation(0)
self.list.setHeaderLabels([prop.title() for prop in properties])
self.list.header().setSectionResizeMode(QHeaderView.Fixed)
self.list.header().setSectionResizeMode(1, QHeaderView.Stretch)
self.list.header().setStretchLastSection(False)
self.list.sortByColumn(0, Qt.AscendingOrder)
self.list.setSortingEnabled(True)
if cues is not None:
self.add_cues(cues)
self.setLayout(QVBoxLayout())
self.layout().addWidget(self.list)
self.buttons = QDialogButtonBox(self)
self.buttons.addButton(QDialogButtonBox.Cancel)
self.buttons.addButton(QDialogButtonBox.Ok)
self.layout().addWidget(self.buttons)
self.buttons.accepted.connect(self.accept)
self.buttons.rejected.connect(self.reject)
def add_cue(self, cue):
item = QTreeWidgetItem()
item.setTextAlignment(0, Qt.AlignCenter)
for n, prop in enumerate(self._properties):
try:
item.setData(n, Qt.DisplayRole, getattr(cue, prop, 'Undefined'))
except Exception as e:
logging.exception('Cannot display {0} property'.format(prop), e,
dialog=False)
self._cues[cue] = item
item.setData(0, Qt.UserRole, cue)
self.list.addTopLevelItem(item)
def add_cues(self, cues):
self.list.setSortingEnabled(False)
for cue in cues:
self.add_cue(cue)
self.list.setSortingEnabled(True)
def remove_cue(self, cue):
index = self.list.indexOfTopLevelItem(self._cues.pop(cue))
self.list.takeTopLevelItem(index)
def reset(self):
self.list.clear()
self._cues.clear()
def selected_cues(self):
cues = []
for item in self.list.selectedItems():
cues.append(item.data(0, Qt.UserRole))
return cues