本文整理汇总了Python中PyQt5.QtWidgets.QTreeWidget.selectedItems方法的典型用法代码示例。如果您正苦于以下问题:Python QTreeWidget.selectedItems方法的具体用法?Python QTreeWidget.selectedItems怎么用?Python QTreeWidget.selectedItems使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类PyQt5.QtWidgets.QTreeWidget
的用法示例。
在下文中一共展示了QTreeWidget.selectedItems方法的8个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: ChangedDocumentsListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [as 别名]
#.........这里部分代码省略.........
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)
def slotButtonReload(self):
"""Called when the user clicks Reload."""
self.reloadDocuments(self.selectedDocuments())
def slotButtonReloadAll(self):
"""Called when the user clicks Reload All."""
self.reloadDocuments(self.allDocuments())
def slotButtonSave(self):
"""Called when the user clicks Save."""
self.saveDocuments(self.selectedDocuments())
示例2: JackConnectionsDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [as 别名]
class JackConnectionsDialog(QDialog):
def __init__(self, jack_client, parent=None, **kwargs):
super().__init__(parent)
self.resize(600, 400)
self.setLayout(QGridLayout())
# self.layout().setContentsMargins(0, 0, 0, 0)
self.output_widget = QTreeWidget(self)
self.output_widget.setHeaderLabels(['Output ports'])
self.input_widget = QTreeWidget(self)
self.input_widget.setHeaderLabels(['Input ports'])
self.connections_widget = ConnectionsWidget(self.output_widget,
self.input_widget,
parent=self)
self.output_widget.itemExpanded.connect(self.connections_widget.update)
self.output_widget.itemCollapsed.connect(self.connections_widget.update)
self.input_widget.itemExpanded.connect(self.connections_widget.update)
self.input_widget.itemCollapsed.connect(self.connections_widget.update)
self.input_widget.itemSelectionChanged.connect(
self.__input_selection_changed)
self.output_widget.itemSelectionChanged.connect(
self.__output_selection_changed)
self.layout().addWidget(self.output_widget, 0, 0)
self.layout().addWidget(self.connections_widget, 0, 1)
self.layout().addWidget(self.input_widget, 0, 2)
self.layout().setColumnStretch(0, 2)
self.layout().setColumnStretch(1, 1)
self.layout().setColumnStretch(2, 2)
self.connectButton = QPushButton('Connect', self)
self.connectButton.clicked.connect(self.__disconnect_selected)
self.connectButton.setEnabled(False)
self.layout().addWidget(self.connectButton, 1, 1)
self.dialogButtons = QDialogButtonBox(
QDialogButtonBox.Cancel | QDialogButtonBox.Ok)
self.dialogButtons.accepted.connect(self.accept)
self.dialogButtons.rejected.connect(self.reject)
self.layout().addWidget(self.dialogButtons, 2, 0, 1, 3)
self.__jack_client = jack_client
self.__selected_in = None
self.__selected_out = None
self.connections = []
self.update_graph()
def set_connections(self, connections):
self.connections = connections
self.connections_widget.connections = self.connections
self.connections_widget.update()
def update_graph(self):
input_ports = self.__jack_client.get_ports(is_audio=True, is_input=True)
self.output_widget.clear()
for port in range(8):
self.output_widget.addTopLevelItem(
QTreeWidgetItem(['output_' + str(port)]))
self.input_widget.clear()
clients = {}
for port in input_ports:
client_name = port.name[:port.name.index(':')]
if client_name not in clients:
clients[client_name] = ClientItem(client_name)
self.input_widget.addTopLevelItem(clients[client_name])
clients[client_name].add_port(port.name)
def __input_selection_changed(self):
if self.input_widget.selectedItems():
self.__selected_in = self.input_widget.selectedItems()[0]
else:
self.__selected_in = None
self.__check_selection()
def __output_selection_changed(self):
if self.output_widget.selectedItems():
self.__selected_out = self.output_widget.selectedItems()[0]
else:
self.__selected_out = None
self.__check_selection()
def __check_selection(self):
if self.__selected_in is not None and self.__selected_out is not None:
output = self.output_widget.indexOfTopLevelItem(self.__selected_out)
self.connectButton.clicked.disconnect()
self.connectButton.setEnabled(True)
#.........这里部分代码省略.........
示例3: PugdebugExpressionViewer
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [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: MainWindow
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [as 别名]
class MainWindow(QMainWindow):
def __init__(self):
super(MainWindow, self).__init__()
self.dbm_obj = Dbm()
self.curFile = ''
self.textEdit = QTextEdit()
self.sectionTreeWidget = QTreeWidget()
self.notesListWidget = QListWidget()
self.createHorizontalGroupBox()
self.setCentralWidget(self.horizontalGroupBox)
self.createActions()
self.createMenus()
# self.createToolBars()
self.createStatusBar()
self.readSettings()
[self.hierarchy_dict, self.notebook_dict, self.section_dict, self.page_dict] = [{}, {}, {}, {}]
self.setCurrentFile('')
# For binding slots and signals
self.fetchPageThread = FetchPage()
self.fetchPageThread.setObjectName('fetchPageThread')
self.syncAllThread = SyncAllThread()
self.syncAllThread.setObjectName('syncAllThread')
self.textEdit.document().contentsChanged.connect(self.documentWasModified)
self.sectionTreeWidget.setObjectName("sectionTreeWidget")
self.notesListWidget.setObjectName("notesListWidget")
QMetaObject.connectSlotsByName(self)
self.readDB()
@pyqtSlot()
def on_sectionTreeWidget_itemSelectionChanged(self):
for x in self.sectionTreeWidget.selectedItems():
if x.text(1) in self.section_dict.keys():
self.populate_notes_list(x.parent().text(1), x.text(1))
@pyqtSlot()
def on_notesListWidget_itemSelectionChanged(self):
for x in self.notesListWidget.selectedItems():
self.fetchPageThread.fetchSignal.connect(self.on_fetchPageThread_fetchComplete)
self.titleLabel.setText("Syncing")
self.statusBar().showMessage("Syncing")
# self.fetchPageThread.fetchSignal.connect(lambda:self.view.setHtml("<body>hello world</body>"))
self.fetchPageThread.fetch(self.page_dict[x.data(1)])
def on_fetchPageThread_fetchComplete(self, string):
self.view.setHtml(string)
self.titleLabel.setText(self.view.title())
self.statusBar().showMessage("Page fetched")
def on_syncAllThread_syncComplete(self, dbm):
self.dbm_obj = dbm
self.statusBar().showMessage("Sync complete")
def createHorizontalGroupBox(self):
self.horizontalGroupBox = QGroupBox()
layout = QHBoxLayout()
self.sectionTreeWidget.setHeaderHidden(1)
layout.addWidget(self.sectionTreeWidget, 0)
self.sectionTreeWidget.setStyleSheet("background-color: rgb(215,227,229)")
self.notesListWidget.setWindowTitle('Notes')
layout.addWidget(self.notesListWidget, 0)
self.notesListWidget.setStyleSheet("QListWidget {background-color: rgb(196,226,233)}")
subVBox = QGroupBox()
vLayout = QVBoxLayout()
self.titleLabel = QLabel()
vLayout.addWidget(self.titleLabel, 0)
self.view = QWebView()
vLayout.addWidget(self.view, 1)
subVBox.setLayout(vLayout)
layout.addWidget(subVBox, 1)
self.horizontalGroupBox.setLayout(layout)
def closeEvent(self, event):
if self.maybeSave():
self.writeSettings()
event.accept()
else:
event.ignore()
def newFile(self):
self.readDB()
# if self.maybeSave():
# self.textEdit.clear()
# self.setCurrentFile('')
def open(self):
if self.maybeSave():
fileName, _ = QFileDialog.getOpenFileName(self)
if fileName:
#.........这里部分代码省略.........
示例5: select_param
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [as 别名]
class select_param(QWidget):
def init(self,treeview):
self.dest_treeview=treeview
def __init__(self):
QWidget.__init__(self)
self.win_list=windows()
self.setFixedSize(400,700)
self.main_vbox=QVBoxLayout()
self.setWindowIcon(QIcon(os.path.join(get_image_file_path(),"scan.png")))
self.setWindowTitle(_("Select simulation parameter (www.gpvdm.com)"))
self.tab = QTreeWidget()
#self.tab.setHeaderItem("Scan items")
self.main_vbox.addWidget(self.tab)
self.hwidget=QWidget()
okButton = QPushButton("OK")
cancelButton = QPushButton("Cancel")
hbox = QHBoxLayout()
hbox.addStretch(1)
hbox.addWidget(okButton)
hbox.addWidget(cancelButton)
self.hwidget.setLayout(hbox)
self.main_vbox.addWidget(self.hwidget)
self.setLayout(self.main_vbox)
okButton.clicked.connect(self.tree_apply_click)
cancelButton.clicked.connect(self.close)
#self.tab.itemSelectionChanged.connect(self.tree_apply_click)
self.tab.header().close()
self.update()
return
def make_entry(self,root,text):
depth=0
pointer=root
for depth in range(0,len(text)):
found=False
for i in range(0,pointer.childCount()):
if pointer.child(i).text(0)==text[depth]:
found=True
pointer=pointer.child(i)
break
if found==False:
pointer=QTreeWidgetItem(pointer, [text[depth]])
def update(self):
self.tab.clear()
root = QTreeWidgetItem(self.tab, [_("Simulation parameters")])
root.setExpanded(True)
param_list=scan_items_get_list()
i=0
for item in range(0, len(param_list)):
div_str=param_list[item].name.replace("\\", "/")
div_str=div_str.split("/")
piter=None
self.make_entry(root,div_str)
def on_destroy(self):
self.win_list.update(self,"scan_select")
self.hide()
return True
def cal_path(self):
getSelected = self.tab.selectedItems()
if getSelected:
item = getSelected[0]
# getChildNode = baseNode.text(0)
path = []
while item is not None:
path.append(str(item.text(0)))
item = item.parent()
ret="/".join(reversed(path))
ret=ret.split('/', 1)[-1]
ret=ret.replace("/", os.path.sep)
return ret
def tree_apply_click(self):
index = self.dest_treeview.selectionModel().selectedRows()
if len(index)>0:
#.........这里部分代码省略.........
示例6: Window
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [as 别名]
#.........这里部分代码省略.........
sourceable_step_names = []
sourceable_steps = self.uj.find_steps_by_attribute('name_user_defined', True)
if sourceable_steps:
self.ddi_response_source_step.reset_items({ str(z.id):z.name for z in sourceable_steps })
sourceable_step_names = [ z.name for z in sourceable_steps ]
self.correlated_names = { z.field_name:z.field_name for z in self.uj.find_ddis_by_attribute('type', 'AUTOCORR') } # if z.field_type == 'Repeated Fields' }
self.ddi_auto_correlate_name.reset_items(self.correlated_names)
groupnodes = []
for stepgroup in self.uj.stepgroups:
new_group_node = QTreeWidgetItem()
new_group_node.setText(0, stepgroup.name)
stepnodes = []
for step in stepgroup.steps:
new_step_node = QTreeWidgetItem(new_group_node)
new_step_node.setText(0, step.name)
stepnodes.append(new_step_node)
groupnodes.append(new_group_node)
self.step_tree.addTopLevelItems(groupnodes)
self.step_flow_response_table.reset_row_template([('Response Step', sourceable_step_names), ('Match Criteria', ''), ('Step', ['Next Step'] + sourceable_step_names + ['End Cycle', 'End User']), ('Sleep Time', '0.0')])
self.step_flow_percentage_table.reset_row_template([('Percentage', ''), ('Step', ['Next Step'] + sourceable_step_names + ['End Cycle', 'End User']), ('Sleep Time', '0.0')])
# self.step_flow_percentage_table.set_text([['100', {'Next Step': ['Next Step', 'End Cycle', 'End User']}, '0.0']])
def export_uj(self):
pass
# convert SIPHON_TYPES from full text to code before passing them to self.uj...
def show_ddi_details(self):
selected_ddi_name = self.ddi_tree.selectedItems()[0].text(0)
self.selected_ddi = self.uj.find_ddi_by_name(selected_ddi_name)
# Common
self.ddi_name.set_text(selected_ddi_name)
self.ddi_description.set_text(self.selected_ddi.description)
self.ddi_type.set_text(DDI_TYPES[self.selected_ddi.type])
self.ddi_sharing.set_text(self.selected_ddi.scope)
self.ddi_refresh.set_text(self.selected_ddi.lifecycle)
# Specific
ddi_specific_fields = [
self.ddi_value_widget,
self.ddi_selector_widget,
self.ddi_delimiter_character_widget,
self.ddi_delimited_filename_widget,
self.ddi_delimited_file_picker_button,
self.ddi_column_index_widget,
self.ddi_date,
self.ddi_list_table,
self.ddi_related_ddi,
self.ddi_response_source_step,
self.ddi_siphon_table,
self.ddi_auto_correlate_type,
self.ddi_auto_correlate_name,
self.ddi_auto_correlate_appears_in,
self.ddi_auto_increment_starting_value,
self.ddi_auto_increment_increment,
self.ddi_auto_increment_prefix,
self.ddi_auto_increment_suffix,
self.ddi_auto_increment_min_lenght,
]
示例7: CueListDialog
# 需要导入模块: from PyQt5.QtWidgets import QTreeWidget [as 别名]
# 或者: from PyQt5.QtWidgets.QTreeWidget import selectedItems [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 selectedItems [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