def moveSelection(self, parent, position): # self.selectedIndexes() is the selected QTreeWidgets' QModelIndex # position type:int and position type:QTreeWidget is the target to put # save the selected items' persistentQindex. if we use QModelIndex, it will change after 1 moved selection = [ QtCore.QPersistentModelIndex(i) for i in self.selectedIndexes() ] print("{} {} {}".format(position, i, QtCore.QPersistentModelIndex(i))) parent_index = self.indexFromItem( parent) #from parent type:TreeWidgetItem to get its QModelIndex if parent_index in selection: return False # save the drop location in case it gets moved since it doesn't exist yet (no previous item) target = self.model().index(position, 0, parent_index).row( ) # (row,column=0, index) to get the child's QModelIndex print("position {} target {}".format( position, target)) # target sometimes is -1 when the row is lastone or empty if target < 0: target = position # remove the selected items taken = [] for index in reversed(selection): #index is a QPersistentModelIndex, we need QModelIndex. both are 1-1 mapping print("index.row {} {} type(position):{}".format( index.row(), type(index), type(position))) item = self.itemFromIndex(QtCore.QModelIndex(index)) # indexFromItem vs ItemFromIndex could switch betwen WtreeItem and QModelIndex if item is None or item.parent() is None: taken.append(self.takeTopLevelItem(index.row())) else: taken.append(item.parent().takeChild(index.row())) # insert the selected items at their new positions while taken: if position == -1: # append the items if position not specified if parent_index.isValid(): parent.insertChild(parent.childCount(), taken.pop(0)) else: self.insertTopLevelItem(self.topLevelItemCount(), taken.pop(0)) else: # insert the items at the specified position if parent_index.isValid(): parent.insertChild(min(target, parent.childCount()), taken.pop(0)) else: self.insertTopLevelItem( min(target, self.topLevelItemCount()), taken.pop(0)) return True
def setRowOpts(self, tableWidget, row, col): btn = QtGui.QPushButton(tableWidget) btn.setText('Remove') index = QtCore.QPersistentModelIndex(tableWidget.model().index( row, col)) btn.clicked.connect(lambda: self.removeBankItem(index)) tableWidget.setCellWidget(row, col, btn)
def setSelection(self, selection): """ Set the model item selection. Parameters ---------- selection : QtGui.QItemSelection Item selection. """ if self.values_view.selectionModel() is not None: indices = selection.indexes() pind = defaultdict(list) for index in indices: parent = index.parent() if parent.isValid(): if parent == self.__model.index(parent.row(), parent.column()): pind[parent.row()].append( QtCore.QPersistentModelIndex(index)) else: warnings.warn("Die Die Die") else: # top level index pass self.__selections = pind self.__restoreSelection()
def __init__(self, tree_view, index): super(TreeViewBusyLabel, self).__init__(tree_view.viewport()) self._tree_view = tree_view self._p_index = QtCore.QPersistentModelIndex(index) self._movie = QtGui.QMovie(BUSY_INDICATOR) self._movie.setCacheMode(QtGui.QMovie.CacheAll) self.setAlignment(QtCore.Qt.AlignVCenter | QtCore.Qt.AlignLeft) self.setMovie(self._movie) # catch the tree view resizes to reposition the busy indicator tree_view.viewport().installEventFilter(self) # need to update position if header sections are resized tree_view.header().sectionResized.connect( lambda i, o, n: self._reposition()) # reposition when scrolling occurs for scrollBar in [ tree_view.horizontalScrollBar(), tree_view.verticalScrollBar() ]: scrollBar.valueChanged.connect(lambda v: self._reposition())
def currentChanged(self, current, previous): """This slot is automatically called when the current item changes. The slot is not called if the item doesn't actually changed. When the current item changes the menus, toolbars and statusbar have to be updated. Probably some QActions will be enabled and other will be disabled. Also the databases tree and the workspace have to be synchronised again (if possible). :Parameters: - `current`: the index model of the new current item - `previous`: the index model of the previous current item """ QtGui.QTreeView.currentChanged(self, current, previous) self.vtgui.updateActions() self.vtgui.updateStatusBar() # Sync the tree view with the workspace (if needed) but keep the # focus (giving focus to the workspace when a given item is # selected is counter intuitive) pcurrent = QtCore.QPersistentModelIndex(current) for window in self.vtgui.workspace.subWindowList(): if pcurrent == window.pindex: self.vtgui.workspace.setActiveSubWindow(window) self.setFocus(True)
def layoutAboutToBeChanged(self): """ Store what is about to be changed """ for i in range(0, max(0, min(self.model.rowCount(), 100))): self.changing.append( QtCore.QPersistentModelIndex(self.model.index(i, 0)))
def viewItem(self, index): """Opens items for viewing. """ item = index.internalPointer() supports = item.getSupportedOperations() # If we can't open this item, then don't if not supports & AbstractLDAPTreeItem.SUPPORT_OPEN: self.__logger.debug("Item didn't support open.") return smartObject = index.internalPointer().smartObject() rep = self.getRepForSmartObject(smartObject) # If the smartobject is already open, switch to it if self.isOpen(smartObject): x = self.openTabs[str(rep)] self.tabWidget.setCurrentWidget(x) return # Saves a representation of the opened entry to avoid opening duplicates # and open it x = AdvancedObjectWidget(QtCore.QPersistentModelIndex(index)) x.initModel(smartObject) self.openTabs[str(rep)] = x self.tabWidget.addTab(x, smartObject.getPrettyRDN()) self.tabWidget.setCurrentWidget(x)
def __storeSelection(self, groupind, indices): # Store current values selection for the current group groupind = self.__currentIndex indices = [ QtCore.QPersistentModelIndex(ind) for ind in self.values_view.selectedIndexes() ] self.__selections[groupind] = indices
def addInvoiceItem(self): rowPosition = self.tableWidget.rowCount() self.tableWidget.insertRow(rowPosition) btn = QtGui.QPushButton(self.tableWidget) btn.setText('Remove') index = QtCore.QPersistentModelIndex(self.tableWidget.model().index( rowPosition, 5)) btn.clicked.connect(lambda: self.removeInvoiceItem(index)) self.tableWidget.setCellWidget(rowPosition, 5, btn)
def delete_row(self): index_list = [] for model_index in self.view_table_fparams.selectionModel( ).selectedRows(): index = QtCore.QPersistentModelIndex(model_index) index_list.append(index) for index in index_list: self.model_fparam_table.removeRow(index.row( )) # have to delete row from model, not the view (table_fparams)
def eventFilter(self, widget, event): if widget is self.viewport(): index = self._last_index if event.type() == QtCore.QEvent.MouseMove: index = self.indexAt(event.pos()) elif event.type() == QtCore.QEvent.Leave: index = QtCore.QModelIndex() if index != self._last_index: row = self._last_index.row() column = self._last_index.column() item = self.itemAt(row, column) if item is not None: self.itemExited.emit(item) self.cellExited.emit(row, column) self._last_index = QtCore.QPersistentModelIndex(index) return QtGui.QTreeWidget.eventFilter(self, widget, event)
def __init__(self, index): """Display a given dataset in the MDI area. """ # The main application window self.vtgui = vitables.utils.getVTApp().gui # The data structure (LeafNode/LinkNode instance) whose dataset # is being displayed dbt_model = self.vtgui.dbs_tree_model self.dbt_leaf = dbt_model.nodeFromIndex(index) # The tables.Node instance tied to that data structure pt_node = self.dbt_leaf.node if hasattr(pt_node, 'target'): # The selected item is a link and must be dereferenced leaf = pt_node() else: leaf = pt_node rbuffer = readBuffer.Buffer(leaf) self.leaf_model = leaf_model.LeafModel(rbuffer) self.leaf_view = leaf_view.LeafView(self.leaf_model) super(DataSheet, self).__init__(self.vtgui.workspace) self.setWidget(self.leaf_view) self.setAttribute(QtCore.Qt.WA_DeleteOnClose) # Customize the title bar if not isinstance(leaf.title, unicode): title = unicode(leaf.title, 'utf_8') else: title = leaf.title wtitle = u"{0}\t{1}".format(self.dbt_leaf.name, title) self.setWindowTitle(wtitle) self.setWindowIcon(self.dbt_leaf.icon) # Eventually update the Node menu actions self.dbt_leaf.has_view = True self.vtgui.updateActions() self.pindex = QtCore.QPersistentModelIndex(index) # Connect signals to slots self.aboutToActivate.connect(self.syncTreeView) self.leaf_view.doubleClicked.connect(self.zoomCell)
def moveSelection(self, parent, position): # save the selected items selection = [QtCore.QPersistentModelIndex(i) for i in self.selectedIndexes()] parent_index = self.indexFromItem(parent) if parent_index in selection: return False # save the drop location in case it gets moved target = self.model().index(position, 0, parent_index).row() if target < 0: target = position # remove the selected items taken = [] for index in reversed(selection): item = self.itemFromIndex(QtCore.QModelIndex(index)) if item is None or item.parent() is None: taken.append(self.takeTopLevelItem(index.row())) else: taken.append(item.parent().takeChild(index.row())) # insert the selected items at their new positions while taken: if position == -1: # append the items if position not specified if parent_index.isValid(): parent.insertChild( parent.childCount(), taken.pop(0)) else: self.insertTopLevelItem( self.topLevelItemCount(), taken.pop(0)) else: # insert the items at the specified position if parent_index.isValid(): parent.insertChild(min(target, parent.childCount()), taken.pop(0)) else: self.insertTopLevelItem(min(target, self.topLevelItemCount()), taken.pop(0)) return True
def __init__(self, *args, **kwargs): QtGui.QTreeWidget.__init__(self, *args, **kwargs) self._last_index = QtCore.QPersistentModelIndex() self.viewport().installEventFilter(self) self.setMouseTracking(True) self.setAcceptDrops(True)
def tree2DropEvent(self, event): logging.info("event DropAction: {}".format(event.dropAction())) if event.dropAction() == QtCore.Qt.MoveAction: position = event.pos() if self.tree2.itemAt(position) == self.tree2.currentItem(): logging.error("abort to move to itself") event.ignore() event.setDropAction(QtCore.Qt.IgnoreAction) return False if self.tree2.currentItem(): parent = self.tree2.currentItem().parent() else: parent = self.tree2.invisibleRootItem() item = self.tree2.itemAt(position) p = self.tree2.indexFromItem(item) logging.info("index row p {} {}".format(p.row(), repr(p))) logging.info(type(p)) q = QtCore.QPersistentModelIndex( p) logging.info(type(q)) self.moveSelection(parent, q.row()) event.accept() return True """ selection = [QtCore.QPersistentModelIndex(i) for i in self.tree2.selectedIndexes()] print("{} {} {}".format(position, i, QtCore.QPersistentModelIndex(i))) parent_index = self.tree2.indexFromItem(parent) #from parent type:TreeWidgetItem to get its QModelIndex logging.info("parent_index selection: {} {}".format(parent_index, selection )) if parent_index in selection: event.ignore() event.setDropAction(QtCore.Qt.IgnoreAction) logging.error("abort drop") return False # success. move selected item to new parent if self.tree2.currentItem() and self.tree2.itemAt(position): item = self.tree2.currentItem() if item.parent() != None: item.parent().removeChild(item) else: self.tree2.takeTopLevelItem(self.tree2.indexOfTopLevelItem(item)) self.tree2.itemAt(position).addChild(item) logging.info("move it") else: logging.error("abort drop because do not know how to move") event.ignore() event.setDropAction(QtCore.Qt.IgnoreAction) logging.error("abort drop") return False """ data = event.mimeData() bstream = data.retrieveData("application/atom", QtCore.QVariant.ByteArray) selected = pickle.loads(bstream.toByteArray()) logging.info("drop data is: {}".format(selected) ) # selected is a BTCommand object parent = self.tree2.itemAt(event.pos()) logging.info("event pos {} parent {}".format(event.pos(), repr(parent))) if parent == None: parent = self.tree2.invisibleRootItem() self._genOneNode(selected.getData(), str(selected.name), parent, selected.getField()) event.accept()
def __init__(self, rows, columns, parent=None): QtGui.QTableWidget.__init__(self, rows, columns, parent) self._last_index = QtCore.QPersistentModelIndex() self.viewport().installEventFilter(self)