Esempio n. 1
0
 def select(self,
            uuids,
            lbox: QTreeView = None,
            scroll_to_show_single=True):
     lbox = self.current_set_listbox if lbox is None else lbox
     lbox.clearSelection()
     if not uuids:
         return
     # FUTURE: this is quick and dirty
     rowdict = dict(
         (u, i) for i, u in enumerate(self.doc.current_layer_uuid_order))
     items = QItemSelection()
     q = None
     for uuid in uuids:
         row = rowdict.get(uuid, None)
         if row is None:
             LOG.error(
                 'UUID {} cannot be selected in list view'.format(uuid))
             continue
         q = self.createIndex(row, 0)
         items.select(q, q)
         lbox.selectionModel().select(items, QItemSelectionModel.Select)
         # lbox.setCurrentIndex(q)
     if scroll_to_show_single and len(uuids) == 1 and q is not None:
         lbox.scrollTo(q)
Esempio n. 2
0
    def mapSelectionRightToLeft(self,
                                selection: QItemSelection) -> QItemSelection:
        if not selection.indexes() or not self.connected:
            return QItemSelection()

        if selection[0].model() != self._right_model:
            print("FAIL", selection[0].model(), self._left_model,
                  self._right_model)
        # assert selection[0].model() == self._right_model

        seek_selection = selection
        # assert self.assertSelectionValid(seek_selection)

        for proxy in self._proxy_chain_down[::-1]:
            if not proxy:
                return QItemSelection()
            seek_selection = proxy.mapSelectionToSource(seek_selection)
            # assert self.assertSelectionValid(seek_selection)

        for proxy in self._proxy_chain_up[::-1]:
            if not proxy:
                return QItemSelection()
            seek_selection = proxy.mapSelectionFromSource(seek_selection)
            # assert self.assertSelectionValid(seek_selection)

        return seek_selection
Esempio n. 3
0
 def update_property_fields(self, idx:QtCore.QItemSelection):
     # indexes() returns list of selected items
     # as we only have 1 at a time, return first item and get corresponding row number
     self.logger.debug("Update property fields")
     if not idx.indexes() == []:
         row = idx.indexes()[0].row()
         if self._parent.model_properties.item(row, 1).text() == 'bool':
             self.datamapper_properties.removeMapping(self.inpPropDef)
             self.datamapper_properties.addMapping(self.cmbPropDef, 6)
             self.inpPropVal.setEnabled(False)
             self.inpPropDef.setEnabled(False)
             self.cmbPropMulti.setEnabled(False)
             self.cmbPropEdit.setEnabled(False)
             self.cmbPropDef.setEnabled(True)
         else:
             self.datamapper_properties.addMapping(self.inpPropDef, 6)
             self.datamapper_properties.removeMapping(self.cmbPropDef)
             self.inpPropVal.setEnabled(True)
             self.inpPropDef.setEnabled(True)
             self.cmbPropMulti.setEnabled(True)
             self.cmbPropEdit.setEnabled(True)
             self.cmbPropDef.setEnabled(False)
         self.datamapper_properties.setCurrentIndex(row)
     else:
         self.datamapper_properties.toFirst()
Esempio n. 4
0
        def accepted():
            try:
                shift, n = intintinput_dialog.sbOffset.value(
                ), intintinput_dialog.sbn.value()
                shift = shift % n
                i = 0

                self.selecting = True

                flags = QItemSelectionModel.Select
                selection = QItemSelection()

                for item in self.myModel.iterate_selected_items(
                        skip_groups=True,
                        skip_childs_in_selected_groups=False,
                        clear_selection=True):
                    if i % n == shift:
                        start_index = self.myModel.createIndex(
                            item.row(), 0, item)
                        end_index = self.myModel.createIndex(
                            item.row(), 1, item)

                        selection.select(start_index, end_index)

                    i += 1
                self.selectionModel().select(selection, flags)

            except Exception as ex:
                Logger.message(ex.__str__())
                QMessageBox.warning(self, 'Error', ex.__str__(),
                                    QMessageBox.Ok)
            finally:
                self.selecting = False
Esempio n. 5
0
    def selectionChanged(self, selected, deselected):

        super(TreeView, self).selectionChanged(selected, deselected)

        if self.selecting or self.deleting:
            return

        self.selecting = True

        # select all children if group was selected
        for item in self.myModel.iterate_selected_items(
                skip_groups=False, skip_childs_in_selected_groups=True):
            # help from https://stackoverflow.com/questions/47271494/set-selection-from-a-list-of-indexes-in-a-qtreeview
            if isinstance(item, SpectrumItemGroup):
                # mod = self.model()
                # columns = mod.columnCount() - 1

                length = item.__len__()

                if length == 0:
                    continue

                flags = QItemSelectionModel.Select
                selection = QItemSelection()

                start_index = self.myModel.createIndex(0, 0, item.children[0])
                end_index = self.myModel.createIndex(length - 1, 1,
                                                     item.children[-1])

                selection.select(start_index, end_index)
                self.selectionModel().select(selection, flags)

        self.selecting = False
Esempio n. 6
0
    def update_dependency_fields(self, idx:QtCore.QItemSelection):
        """ Update single fields on dependency tab in relation to selected row in table view"""

        self.logger.debug("Update dependency fields")

        self.cmbDepAction.setEnabled(False)
        self.cmbDepProdID.setEnabled(False)
        self.cmbDepReqAction.setEnabled(False)
        self.cmbDepInstState.setEnabled(False)
        self.cmbDepRequirement.setEnabled(False)
        self.btnDepModify.setEnabled(False)
        self.btnDepAdd.setEnabled(True)

        # disconnect if there has been an editing event before
        try:
            self.cmbDepReqAction.currentIndexChanged.disconnect()
            self.cmbDepInstState.currentIndexChanged.disconnect()
        except:
            pass

        if self.datamapper_dependencies.model().item(0, 0) is not None:
            self.btnDepDelete.setEnabled(True)
            self.btnDepEdit.setEnabled(True)

            # indexes() returns list of selected items
            # as we only have 1 at a time, return first item and get corresponding row number
            if not idx.indexes() == []:
                row = idx.indexes()[0].row()
                self.datamapper_dependencies.setCurrentIndex(row)
            else:
                self.datamapper_dependencies.toFirst()

        else:
            self.btnDepDelete.setEnabled(False)
            self.btnDepEdit.setEnabled(False)
Esempio n. 7
0
 def onSelectionChanged(self, selection: QItemSelection):
     if selection.isEmpty():
         return
     item = selection.indexes()[0]
     data = item.data(ROLE_HTTP_MESSAGE)
     if data:
         self.selected.emit(data)
Esempio n. 8
0
    def _ext_sel_changed(self, selected: QItemSelection,
                         deselected: QItemSelection):
        """
        Selection changed for view.extList, save new selection
        :@param selected: QItemSelection
        :@param deselected: QItemSelection
        :@return: None
        """
        model = self.ui.extList.model()
        for id_ in selected.indexes():
            if model.rowCount(id_) > 0:
                self.ui.extList.setExpanded(id_, True)
                sel = QItemSelection(
                    model.index(0, 0, id_),
                    model.index(
                        model.rowCount(id_) - 1,
                        model.columnCount(id_) - 1, id_),
                )
                self.ui.extList.selectionModel().select(
                    sel, QItemSelectionModel.Select)

        for id_ in deselected.indexes():
            if id_.parent().isValid():
                self.ui.extList.selectionModel().select(
                    id_.parent(), QItemSelectionModel.Deselect)

        self._save_ext_selection()
Esempio n. 9
0
 def setSelectedItems(self, items):
     #block = self.blockSignals(True)
     sel = QItemSelection()
     for item in items:
         sel.merge(QItemSelection(item.index(), item.index(1)), QItemSelectionModel.SelectCurrent)
     if set(sel) != set(self.selectionModel().selection()):
         self.selectionModel().clear()
         self.selectionModel().select(sel, QItemSelectionModel.Select)
Esempio n. 10
0
 def __filter_rowsInserted(self, parent: QModelIndex, start: int,
                           end: int) -> None:
     fmodel = self.__pmodel
     mrange = QItemSelection(fmodel.index(start, 0, parent),
                             fmodel.index(end, 0, parent))
     mranges = fmodel.mapSelectionToSource(mrange)
     for mrange in mranges:
         self.__filter_set(range(mrange.top(), mrange.bottom() + 1), False)
Esempio n. 11
0
    def _do_select(self, start_bindex, end_bindex):
        """
        select the given range by buffer indices

        selects items like this:

            ..................
            ......xxxxxxxxxxxx
            xxxxxxxxxxxxxxxxxx
            xxxxxxxxxxxxxxxxxx
            xxxxxxxxxxxx......
            ..................

        *not* like this:

            ..................
            ......xxxxxx......
            ......xxxxxx......
            ......xxxxxx......
            ......xxxxxx......
            ..................
         """
        self.select(QItemSelection(), QItemSelectionModel.Clear)
        if start_bindex > end_bindex:
            start_bindex, end_bindex = end_bindex, start_bindex

        start_qindex = self._model.index2qindexb(start_bindex)
        start_row = start_qindex.row()
        start_col = start_qindex.column()
        #: binary index of the 1st column on the row containing start_bindex
        start_row_start_idx = start_bindex - start_col
        #: binary index of the last column on the row containing start_bindex
        start_row_end_idx = start_bindex + (0xf-start_col)
        end_qindex = self._model.index2qindexb(end_bindex)
        end_row = end_qindex.row()
        end_col = end_qindex.column()
        end_row_start_idx = end_bindex - end_col
        end_row_end_idx = end_bindex + (0xf-end_col)

        selection = QItemSelection()
        if end_row == start_row:
            # all on one line
            self._bselect(selection, start_bindex, end_bindex)
        elif end_row - start_row == 1:
            # two lines
            self._bselect(selection, start_bindex, start_row_end_idx)
            self._bselect(selection, end_row_start_idx, end_bindex)
        else:
            # many lines
            self._bselect(selection, start_bindex, start_row_end_idx)
            self._bselect(selection, start_row_start_idx + 0x10,
                          end_row_end_idx - 0x10)
            self._bselect(selection, end_row_start_idx, end_bindex)

        self.select(selection, QItemSelectionModel.SelectCurrent)
        self.start = start_bindex
        self.end = end_bindex
        self.selectionRangeChanged.emit(end_bindex)
Esempio n. 12
0
    def on_selection_changed(self, selected: QItemSelection,
                             deselected: QItemSelection):
        for index in selected.indexes():
            item = index.data(AnnotationsModel.ItemRole)
            item.setSelected(True)

        for index in deselected.indexes():
            item = index.data(AnnotationsModel.ItemRole)
            item.setSelected(False)
Esempio n. 13
0
    def changedSelected(self, selected: QtCore.QItemSelection):
        if isinstance(selected, QtCore.QItemSelection):
            if len(selected.indexes()):
                i = selected.indexes()[0].row()
                item = self.fieldlistModel.item(i)

                for field in self.registerLayout.fields:
                    if field.listItem == item:
                        self.registerLayout.setSelected(field)
Esempio n. 14
0
 def update_dependency_fields(self, idx:QtCore.QItemSelection):
     # indexes() returns list of selected items
     # as we only have 1 at a time, return first item and get corresponding row number
     self.logger.debug("Update dependency fields")
     if not idx.indexes() == []:
         row = idx.indexes()[0].row()
         self.datamapper_dependencies.setCurrentIndex(row)
     else:
         self.datamapper_dependencies.toFirst()
Esempio n. 15
0
 def setSelectedItems(self, items):
     #block = self.blockSignals(True)
     sel = QItemSelection()
     for item in items:
         sel.merge(QItemSelection(item.index(), item.index(1)),
                   QItemSelectionModel.SelectCurrent)
     if set(sel) != set(self.selectionModel().selection()):
         self.selectionModel().clear()
         self.selectionModel().select(sel, QItemSelectionModel.Select)
Esempio n. 16
0
 def _restoreSelection(self):
     newSelection = QItemSelection()
     for index in self.model.selected_indexes:
         newSelection.select(self.createIndex(index, 0), self.createIndex(index, 0))
     self.view.selectionModel().select(newSelection, QItemSelectionModel.ClearAndSelect)
     if len(newSelection.indexes()):
         currentIndex = newSelection.indexes()[0]
         self.view.selectionModel().setCurrentIndex(currentIndex, QItemSelectionModel.Current)
         self.view.scrollTo(currentIndex)
Esempio n. 17
0
 def _set_selection(self, row_list):
     selection = QItemSelection()
     model = self.table.model()
     for row in row_list:
         index = model.index(row, 0)
         selection.select(index, index)
     self.table.selectionModel().select(selection, QItemSelectionModel.Rows |
                                        QItemSelectionModel.ClearAndSelect |
                                        QItemSelectionModel.Current)
Esempio n. 18
0
 def _set_selection(self, row_list):
     selection = QItemSelection()
     model = self.table.model()
     for row in row_list:
         index = model.index(row, 0)
         selection.select(index, index)
     self.table.selectionModel().select(selection, QItemSelectionModel.Rows |
                                        QItemSelectionModel.ClearAndSelect |
                                        QItemSelectionModel.Current)
 def selected_layer_selection_changed(self, selected: QtCore.QItemSelection,
                                      deselected: QtCore.QItemSelection):
     if len(selected.indexes()) > 0 and self.validate_layer_rb.isChecked():
         self.toggle_other_pages(True)
         # TODO: check if self.dataset is None
         self.dataset = self._get_current_layer()
     elif len(selected.indexes()) == 0 and self.validate_layer_rb.isChecked(
     ):
         self.toggle_other_pages(False)
         self.dataset = None
Esempio n. 20
0
 def _set_selection(self, row_list):
     selection = QItemSelection()
     model = self.table.model()
     for row in row_list:
         if self._reverse_order:
             row = len(self._config_dictionaries) - row - 1
         index = model.index(row, 0)
         selection.select(index, index)
     self.table.selectionModel().select(selection, QItemSelectionModel.Rows |
                                        QItemSelectionModel.ClearAndSelect |
                                        QItemSelectionModel.Current)
Esempio n. 21
0
 def _set_selection(self, row_list):
     selection = QItemSelection()
     model = self.table.model()
     for row in row_list:
         if self._reverse_order:
             row = len(self._config_dictionaries) - row - 1
         index = model.index(row, 0)
         selection.select(index, index)
     self.table.selectionModel().select(
         selection, QItemSelectionModel.Rows
         | QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Current)
Esempio n. 22
0
 def _on_selection_change(
     self,
     selected: QtCore.QItemSelection,
     _deselected: QtCore.QItemSelection,
 ) -> None:
     if len(selected.indexes()) == 1:
         self.setEnabled(True)
         self._mapper.set_current_index(selected.indexes()[0].row())
     else:
         self.setEnabled(False)
         self._mapper.set_current_index(None)
Esempio n. 23
0
    def _apply_selection_to_full_row(self):
        rows = list()
        selection = QItemSelection()
        for idx in self.selectedIndexes():
            if idx.row() not in rows:
                rows.append(idx.row())
                selection.append(QItemSelectionRange(idx))

        self.selectionModel().select(
            selection,
            QItemSelectionModel.Rows | QItemSelectionModel.ClearAndSelect)
Esempio n. 24
0
 def _updateViewSelection(self):
     # Takes the selection on the model's side and update the view with it.
     newSelection = QItemSelection()
     columnCount = self.columnCount(QModelIndex())
     for index in self.model.selected_indexes:
         newSelection.select(self.createIndex(index, 0), self.createIndex(index, columnCount-1))
     self.view.selectionModel().select(newSelection, QItemSelectionModel.ClearAndSelect)
     if len(newSelection.indexes()):
         currentIndex = newSelection.indexes()[0]
         self.view.selectionModel().setCurrentIndex(currentIndex, QItemSelectionModel.Current)
         self.view.scrollTo(currentIndex)
Esempio n. 25
0
    def selectionChanged(self, selected: QItemSelection,
                         deselected: QItemSelection) -> None:
        # WARNING: selectionChanged will be called before init()
        if not hasattr(self, "animation_data"):
            return

        for index in selected.indexes():
            name = self.model.itemFromIndex(index).text()
            self.animation_data.select(name)

        for index in deselected.indexes():
            name = self.model.itemFromIndex(index).text()
            self.animation_data.deselect(name)

        for sequence in self.animation_data.selected:
            sequence.select_all()

        self.animation_data_changed.emit()

        #
        # for index in deselected.indexes():
        # 	item = self.model.itemFromIndex(index)
        # 	if item.parent() is None:
        # 		pass
        # 	else:
        # 		deselected_frames.append(item)
        #
        # if len(selected_sequences) != 0:
        # 	# Change to this sequence
        # 	self.animation_data.active_sequence = self.animation_data.get_sequence(selected_sequences[0].text())
        # 	self.animation_data_changed_signal.emit()
        # 	self.clearSelection()
        # 	#self.selectionModel().select(selected_sequences[0].index(), QItemSelectionModel.Select)
        #
        # elif len(selected_frames) != 0 or len(deselected_frames) != 0:
        # 	# Only frames have been selected
        # 	for index in selected.indexes():
        # 		# Add frames to selection
        # 		item = self.model.itemFromIndex(index)
        # 		if item.parent() is not None:
        # 			self.animation_data.active_sequence.select(int(item.text()))
        #
        # 	for index in deselected.indexes():
        # 		# Remove frames from selection
        # 		item = self.model.itemFromIndex(index)
        # 		if item.parent() is not None:
        # 			self.animation_data.active_sequence.deselect(int(item.text()))
        #
        # 	self.animation_data_changed_signal.emit()

        super(SpritesheetAnimationList,
              self).selectionChanged(selected, deselected)
 def on_btnCheckAll_clicked(self):
     sel = self.tableView.selectionModel()
     # block_old = sel.blockSignals(True)
     sel_modified = False
     s = QItemSelection()
     for row_idx, utxo in enumerate(self.utxos):
         index = self.table_model.index(row_idx, 0)
         if not utxo['coinbase_locked'] and not utxo.get('spent_date'):
             if not sel.isSelected(index):
                 sel_modified = True
                 s.select(index, index)
     if sel_modified:
         sel.select(s, QItemSelectionModel.ClearAndSelect | QItemSelectionModel.Rows)
Esempio n. 27
0
    def handle_submit(self):
        """Handle submit button click.

        On submit button click, we try to push the finish times for the selected rows to the
        corresponding racer. For each selection that succeeds, we remove that row from this table.
        """
        race_table_model = self.modeldb.race_table_model

        selection_list = self.selectionModel().selectedRows()

        # Remove rows from large to small, because the rows are removed
        # immediately, and cause the rest of the rows to shift, invalidating
        # any row number that's higher than the currently removed one.
        selection_list.sort(key=lambda selection: selection.row(),
                            reverse=True)
        deleted_selection = QItemSelection()
        for selection in selection_list:
            try:
                # Only try to submit it if it's a non-negative integer.
                # Else, it is obviously a work in progress, so don't even
                # bother.
                record = self.source_model.record(selection.row())
                scratchpad = record.value(ResultTableModel.SCRATCHPAD)
                if scratchpad.isdigit():
                    self.source_model.submit_result(selection.row())
                    deleted_selection.select(selection, selection)

                    reference_datetime = race_table_model.get_reference_clock_datetime(
                    )
                    bib = record.value(ResultTableModel.SCRATCHPAD)
                    msecs = record.value(ResultTableModel.FINISH)
                    finish = reference_datetime.addMSecs(msecs).toString(
                        defaults.DATETIME_FORMAT)

                    self.journal.log(
                        'Result with bib "%s" and time "%s" submitted.' %
                        (bib, finish))

            except InputError as e:
                QMessageBox.warning(self, 'Error', str(e))

        # Model retains blank rows until we select() again.
        self.source_model.select()

        # Surprisingly, when the model changes such that our selection changes
        # (for example, when the selected result gets submitted to the racer
        # table model and gets deleted from the result table model), the
        # selectionChanged signal is NOT emitted. So, we have to emit that
        # ourselves here.
        self.selectionModel().selectionChanged.emit(QItemSelection(),
                                                    deleted_selection)
    def selectionFilter(self, selected_items: QItemSelection,
                        deselected_items: QItemSelection):
        """Disables selections of items not in the active filter set.
        I had issues with segfaults subclassing QItemSelectionModel so
        this is the next best thing I think
        """

        # NOTE: prevent selection when select is not pressed
        is_not_select_tool = not self._window.action_global_select.isChecked()

        document = self._document
        # print("!!!!!!!!filter", len(selected_items), len(deselected_items))
        if self.selection_filter_disabled:
            return
        filter_set = document.filter_set
        filter_set.add('part')
        out_deselection = []
        out_selection = []
        flags = QItemSelectionModel.Current | QItemSelectionModel.Deselect
        for index in selected_items.indexes():
            item = self.itemFromIndex(index)
            if is_not_select_tool or item.FILTER_NAME not in filter_set:
                if index.column() == 0:
                    # print("deselect", item.FILTER_NAME, filter_set,
                    #                     index.row(), index.column())
                    out_deselection.append(index)
            else:
                out_selection.append(index)
        sm = self.selectionModel()
        if len(out_deselection) > 0:
            self.indexFromItem(item)
            deselection = QItemSelection(out_deselection[0],
                                         out_deselection[-1])
            sm.blockSignals(True)
            sm.select(deselection, flags)
            sm.blockSignals(False)

        # now group the indices into items in sets
        tbs, tbd = self.model_selection_changes
        # print("sets:", tbs, tbd)
        for idx in out_selection:
            item = self.itemFromIndex(idx)
            # print("did select", item)
            tbs.add(item)
        for idx in deselected_items.indexes():
            # print("could deselect?", self.itemFromIndex(idx))
            item = self.itemFromIndex(idx)
            if item not in tbd and item.isModelSelected(document):
                tbd.add(item)
        self.processSelections(deselect_only=True)
Esempio n. 29
0
    def _on_selection_changed(self, selection: QItemSelection):
        if len(selection.indexes()) != 0:
            modelIndex: QModelIndex = selection.indexes()[0]
            index = modelIndex.row()
            tables = self._appModel.get_tables()
            if index not in self._listViewIndexToTabIndex:
                table_name = tables[index]
                new_tab = self._create_new_tab(table_name)
                self.tablesTabs.addTab(new_tab.view, table_name)
                self._listViewIndexToTabIndex[index] = self.tablesTabs.count(
                ) - 1

            self.tablesTabs.setCurrentIndex(
                self._listViewIndexToTabIndex[index])
Esempio n. 30
0
 def _on_selection_change(
     self,
     selected: QItemSelection,
     _deselected: QItemSelection,
 ) -> None:
     anything_selected = len(selected.indexes()) > 0
     self._remove_button.setEnabled(anything_selected)
     self._rename_button.setEnabled(anything_selected)
     self._duplicate_button.setEnabled(anything_selected)
     self._move_up_button.setEnabled(anything_selected
                                     and selected.indexes()[0].row() > 0)
     self._move_down_button.setEnabled(
         anything_selected
         and selected.indexes()[0].row() < len(self._api.subs.styles) - 1)
Esempio n. 31
0
    def selectTilesInStamp(self, stamp):
        if self.mEmittingStampCaptured:
            return
        processed = QSet()
        selections = QMap()
        for variation in stamp.variations():
            tileLayer = variation.tileLayer()
            for cell in tileLayer:
                tile = cell.tile
                if tile:
                    if (processed.contains(tile)):
                        continue
                    processed.insert(tile)  # avoid spending time on duplicates
                    tileset = tile.tileset()
                    tilesetIndex = self.mTilesets.indexOf(
                        tileset.sharedPointer())
                    if (tilesetIndex != -1):
                        view = self.tilesetViewAt(tilesetIndex)
                        if (not view.model()):  # Lazily set up the model
                            self.setupTilesetModel(view, tileset)
                        model = view.tilesetModel()
                        modelIndex = model.tileIndex(tile)
                        selectionModel = view.selectionModel()

                        _x = QItemSelection()
                        _x.select(modelIndex, modelIndex)
                        selections[selectionModel] = _x

        if (not selections.isEmpty()):
            self.mSynchronizingSelection = True
            # Mark captured tiles as selected
            for i in selections:
                selectionModel = i[0]
                selection = i[1]
                selectionModel.select(selection,
                                      QItemSelectionModel.SelectCurrent)

            # Show/edit properties of all captured tiles
            self.mMapDocument.setSelectedTiles(processed.toList())
            # Update the current tile (useful for animation and collision editors)
            first = selections.first()
            selectionModel = first[0]
            selection = first[1]
            currentIndex = QModelIndex(selection.first().topLeft())
            if (selectionModel.currentIndex() != currentIndex):
                selectionModel.setCurrentIndex(currentIndex,
                                               QItemSelectionModel.NoUpdate)
            else:
                self.currentChanged(currentIndex)
            self.mSynchronizingSelection = False
Esempio n. 32
0
    def selectionFilter(self,   selected_items: QItemSelection,
                                deselected_items: QItemSelection):
        """Disables selections of items not in the active filter set.
        I had issues with segfaults subclassing QItemSelectionModel so
        this is the next best thing I think
        """

        # NOTE: prevent selection when select is not pressed
        is_not_select_tool = not self._window.action_global_select.isChecked()

        document = self._document
        # print("!!!!!!!!filter", len(selected_items), len(deselected_items))
        if self.selection_filter_disabled:
            return
        filter_set = document.filter_set
        filter_set.add('part')
        out_deselection = []
        out_selection = []
        flags = QItemSelectionModel.Current | QItemSelectionModel.Deselect
        for index in selected_items.indexes():
            item = self.itemFromIndex(index)
            if is_not_select_tool or item.FILTER_NAME not in filter_set:
                if index.column() == 0:
                    # print("deselect", item.FILTER_NAME, filter_set,
                    #                     index.row(), index.column())
                    out_deselection.append(index)
            else:
                out_selection.append(index)
        sm = self.selectionModel()
        if len(out_deselection) > 0:
            self.indexFromItem(item)
            deselection = QItemSelection(out_deselection[0], out_deselection[-1])
            sm.blockSignals(True)
            sm.select(deselection, flags)
            sm.blockSignals(False)

        # now group the indices into items in sets
        tbs, tbd = self.model_selection_changes
        # print("sets:", tbs, tbd)
        for idx in out_selection:
            item = self.itemFromIndex(idx)
            # print("did select", item)
            tbs.add(item)
        for idx in deselected_items.indexes():
            # print("could deselect?", self.itemFromIndex(idx))
            item = self.itemFromIndex(idx)
            if item not in tbd and item.isModelSelected(document):
                tbd.add(item)
        self.processSelections(deselect_only=True)
Esempio n. 33
0
 def setChanged(self,
                topLeft: QModelIndex,
                bottomRight: QModelIndex = None):
     """Set the item and all parents as changed"""
     bottomRight = topLeft if bottomRight is None else bottomRight
     if topLeft.isValid() and bottomRight.isValid():
         selection = QItemSelection(topLeft, bottomRight)
         for index in selection.indexes():
             self.objByIndex(index).changed = True
             if index.parent().isValid():
                 self.setChanged(index.parent())
             else:
                 packItem: QModelIndex = index.data(PACK_ITEM_ROLE)
                 if packItem and packItem.isValid():
                     packItem.model().dataChanged.emit(packItem, packItem)
Esempio n. 34
0
    def _event_selection_changed(self, selected: QItemSelection, deselected: QItemSelection) \
            -> None:
        # Selecting an entry should change the page elements to be ready to either move to another
        # page, or whatever else is applicable.
        if len(selected.indexes()):
            wallet_path = self._recent_wallet_paths[selected.indexes()[0].row()]
            entry = self._recent_wallet_entries[wallet_path]
            if entry.requires_upgrade:
                self._next_page_id = WalletPage.MIGRATE_OLDER_WALLET
            else:
                self._next_page_id = -1
        else:
            self._clear_selection()

        self.completeChanged.emit()
Esempio n. 35
0
 def select_label(self, label: ActionLabel):
     logger.debug(label)
     logger.debug(QRect(label.begin, label.timeline_row, label.end - label.begin + 1, 1))
     self.selectionModel().select(
         QItemSelection(self.model().index(label.timeline_row, label.begin),
                        self.model().index(label.timeline_row, label.end)),
         QItemSelectionModel.ClearAndSelect)
Esempio n. 36
0
    def remove_participants(self, selection: QItemSelection):
        if len(self.participants) < 1:
            return

        if selection.isEmpty():
            start, end = len(self.participants) - 1, len(self.participants) - 1  # delete last element
        else:
            start, end = min([rng.top() for rng in selection]), max([rng.bottom() for rng in selection])

        del self.participants[start:end + 1]
        num_removed = (end + 1) - start
        for participant in self.participants:
            if participant.relative_rssi > len(self.participants) - 1:
                participant.relative_rssi -= num_removed

        # fix duplicates
        n = len(self.participants)
        for p1, p2 in itertools.combinations(self.participants, 2):
            if p1.relative_rssi == p2.relative_rssi:
                p1.relative_rssi = next((i for i in range(n)
                                         if i not in set(p.relative_rssi for p in self.participants)),
                                        0)

        self.update()
        self.participant_edited.emit()
Esempio n. 37
0
    def dataColumnView_selectionChanged(self, selected: QtCore.QItemSelection,
                                        deselected: QtCore.QItemSelection):
        """
        The selection has been changed. Used to enable/disable the actions (add ingredient/delete) and to
        load the stacked widget

        Args:
            selected (): Selected indexes
            deselected (): Deselected index

        Returns:

        """

        self.toggle_actions(selected.indexes())
        self.load_stackedwidget(selected.indexes())
Esempio n. 38
0
 def select_row(self, style):
     style = style.lower()
     selectionModel = self.list.selectionModel()
     parent = QModelIndex()
     self.rows = self.model.rowCount(parent) - 1
     if style == 'last':
         self.row = self.rows
         print 'last =', self.row
     elif style == 'up':
         if self.row > 0:
             self.row -= 1
         else:
             self.row = 0
     elif style == 'down':
         if self.row < self.rows:
             self.row += 1
         else:
             self.row = self.rows
     else:
         return
     top = self.model.index(self.row, 0, parent)
     bottom = self.model.index(self.row, 0, parent)
     selectionModel.setCurrentIndex(
         top, QItemSelectionModel.Select | QItemSelectionModel.Rows)
     selection = QItemSelection(top, top)
     selectionModel.clearSelection()
     selectionModel.select(selection, QItemSelectionModel.Select)
Esempio n. 39
0
    def select_row(self, style):
        style = style.lower()
        selectionModel = self.list.selectionModel()
        row = selectionModel.currentIndex().row()
        self.rows = self.model.rowCount(self.list.rootIndex())

        if style == 'last':
            row = self.rows
        elif style == 'up':
            if row > 0:
                row -= 1
            else:
                row = 0
        elif style == 'down':
            if row < self.rows:
                row += 1
            else:
                row = self.rows
        else:
            return
        top = self.model.index(row, 0, self.list.rootIndex())
        selectionModel.setCurrentIndex(top, QItemSelectionModel.Select | QItemSelectionModel.Rows)
        selection = QItemSelection(top, top)
        selectionModel.clearSelection()
        selectionModel.select(selection, QItemSelectionModel.Select)
Esempio n. 40
0
 def dataChangedSlot(self, top_left: QModelIndex , bottom_right: QModelIndex):
     if self.is_child_adding == 0:
         if top_left == bottom_right:    # single item
             item = self.itemFromIndex(top_left)
             if isinstance(item, (OutlineVirtualHelixItem, OutlineNucleicAcidPartItem, OutlineOligoItem)):
                 # print("dataChanged", item.__class__.__name__)
                 item.updateCNModel()
         else:
             selection = QItemSelection(top_left, bottom_right)
             for index in selection.indexes():
                 if index.column() == 0:
                     item = self.itemFromIndex(index)
                     # if isinstance(item, OutlineVirtualHelixItem):
                     #     print("slap", item.idNum())
                     if isinstance(item, (OutlineVirtualHelixItem, OutlineNucleicAcidPartItem, OutlineOligoItem)):
                         item.updateCNModel()
Esempio n. 41
0
    def _on_selection_changed(self, selected: QItemSelection,
                              deselected: QItemSelection) -> None:
        # Selecting an entry should change the page elements to be ready to either move to another
        # page, or whatever else is applicable.
        selected_page = False
        if len(selected.indexes()):
            wallet_path = self._recent_wallet_entries[selected.indexes()
                                                      [0].row()]['path']
            selected_page = self._attempt_open_wallet(wallet_path)

        # Therefore if there was nothing valid selected with this event, then disable those
        # elements.
        if not selected_page:
            self._reset()

        self.completeChanged.emit()
Esempio n. 42
0
    def update_property_fields(self, idx:QtCore.QItemSelection):
        """ Update single fields on property tab in relation to selected row in table view"""

        self.logger.debug("Update property fields")

        self.inpPropName.setEnabled(False)
        self.cmbPropType.setEnabled(False)
        self.cmbPropMulti.setEnabled(False)
        self.cmbPropEdit.setEnabled(False)
        self.inpPropDesc.setEnabled(False)
        self.inpPropVal.setEnabled(False)
        self.inpPropDef.setEnabled(False)
        self.cmbPropDef.setEnabled(False)
        self.btnPropModify.setEnabled(False)
        self.btnPropAdd.setEnabled(True)

        # disconnect if there has been an editing event before
        try:
            self.cmbPropType.currentIndexChanged.disconnect()
        except:
            pass

        if self.datamapper_properties.model().item(0, 0) is not None:
            self.btnPropDelete.setEnabled(True)
            self.btnPropEdit.setEnabled(True)

            # indexes() returns list of selected items
            # as we only have 1 at a time, return first item and get corresponding row number
            if not idx.indexes() == []:
                row = idx.indexes()[0].row()
                self.datamapper_properties.setCurrentIndex(row)
            else:
                self.datamapper_properties.toFirst()
        else:
            self.btnPropDelete.setEnabled(False)
            self.btnPropEdit.setEnabled(False)

            self.inpPropName.setText("")
            self.inpPropDesc.setText("")
            self.inpPropVal.setText("")
            self.inpPropDef.setText("")
Esempio n. 43
0
    def move_down(self, selection: QItemSelection):
        if selection.isEmpty() or len(self.participants) < 1:
            return None, None

        start, end = min([rng.top() for rng in selection]), max([rng.bottom() for rng in selection])
        if end >= len(self.participants) - 1:
            return None, None

        for i in reversed(range(start, end + 1)):
            self.participants[i], self.participants[i + 1] = self.participants[i + 1], self.participants[i]

        self.update()
        self.participant_edited.emit()

        return start, end
Esempio n. 44
0
 def select(self, row_1, col_1, row_2, col_2):
     selection = QItemSelection()
     start_index = self.model().index(row_1, col_1)
     end_index = self.model().index(row_2, col_2)
     selection.select(start_index, end_index)
     self.selectionModel().select(selection, QItemSelectionModel.Select)
Esempio n. 45
0
    def keyPressEvent(self, event: QKeyEvent):
        if event.key() == Qt.Key_Delete:
            min_row, max_row, start, end = self.selection_range()
            if min_row == max_row == start == end == -1:
                return

            self.setEnabled(False)
            self.setCursor(Qt.WaitCursor)
            self.model().delete_range(min_row, max_row, start, end - 1)
            self.unsetCursor()
            self.setEnabled(True)
            self.setFocus()

        if event.matches(QKeySequence.Copy):
            self.on_copy_action_triggered()
            return

        if event.key() == Qt.Key_Space:
            min_row, max_row, start, _ = self.selection_range()
            if start == -1:
                return

            self.model().insert_column(start, list(range(min_row, max_row + 1)))

        if event.key() not in (Qt.Key_Right, Qt.Key_Left, Qt.Key_Up, Qt.Key_Down) \
                or event.modifiers() == Qt.ShiftModifier:
            super().keyPressEvent(event)
            return

        min_row, max_row, min_col, max_col = self.selection_range()
        if min_row == max_row == min_col == max_col == -1:
            super().keyPressEvent(event)
            return

        max_col -= 1
        scroll_to_start = True

        if event.key() == Qt.Key_Right and max_col < self.model().col_count - 1:
            max_col += 1
            min_col += 1
            scroll_to_start = False
        elif event.key() == Qt.Key_Left and min_col > 0:
            min_col -= 1
            max_col -= 1
        elif event.key() == Qt.Key_Down and max_row < self.model().row_count - 1:
            first_unhidden = -1
            for row in range(max_row + 1, self.model().row_count):
                if not self.isRowHidden(row):
                    first_unhidden = row
                    break

            if first_unhidden != -1:
                sel_len = max_row - min_row
                max_row = first_unhidden
                min_row = max_row - sel_len
                scroll_to_start = False
        elif event.key() == Qt.Key_Up and min_row > 0:
            first_unhidden = -1
            for row in range(min_row - 1, -1, -1):
                if not self.isRowHidden(row):
                    first_unhidden = row
                    break

            if first_unhidden != -1:
                sel_len = max_row - min_row
                min_row = first_unhidden
                max_row = min_row + sel_len

        start = self.model().index(min_row, min_col)
        end = self.model().index(max_row, max_col)

        selection = QItemSelection()
        selection.select(start, end)
        self.setCurrentIndex(start)
        self.selectionModel().setCurrentIndex(end, QItemSelectionModel.ClearAndSelect)
        self.selectionModel().select(selection, QItemSelectionModel.ClearAndSelect)
        if scroll_to_start:
            self.scrollTo(start)
        else:
            self.scrollTo(end)