Python PyQt5.QtCore.QModelIndex() Examples

The following are 30 code examples for showing how to use PyQt5.QtCore.QModelIndex(). These examples are extracted from open source projects. You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example.

You may check out the related API usage on the sidebar.

You may also want to check out all available functions/classes of the module PyQt5.QtCore , or try the search function .

Example 1
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 6 votes vote down vote up
def data(self, index, role=Qt.DisplayRole):
        """Return the item data for index.

        Override QAbstractItemModel::data.

        Args:
            index: The QModelIndex to get item flags for.

        Return: The item data, or None on an invalid index.
        """
        if role != Qt.DisplayRole:
            return None
        cat = self._cat_from_idx(index)
        if cat:
            # category header
            if index.column() == 0:
                return self._categories[index.row()].name
            return None
        # item
        cat = self._cat_from_idx(index.parent())
        if not cat:
            return None
        idx = cat.index(index.row(), index.column())
        return cat.data(idx) 
Example 2
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 6 votes vote down vote up
def index(self, row, col, parent=QModelIndex()):
        """Get an index into the model.

        Override QAbstractItemModel::index.

        Return: A QModelIndex.
        """
        if (row < 0 or row >= self.rowCount(parent) or
                col < 0 or col >= self.columnCount(parent)):
            return QModelIndex()
        if parent.isValid():
            if parent.column() != 0:
                return QModelIndex()
            # store a pointer to the parent category in internalPointer
            return self.createIndex(row, col, self._categories[parent.row()])
        return self.createIndex(row, col, None) 
Example 3
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    License: GNU General Public License v2.0 6 votes vote down vote up
def rowCount(self, parent=QtCore.QModelIndex()):
                '''The number of rows under the given parent.

                When the parent is valid it means that rowCount is returning
                the number of children of parent.

                Args:
                    parent (:obj:`QtCore.QModelIndex`, optional): Parent

                Returns:
                    int: Number of rows
                '''
                if None == self._data:
                    return 0

                return len(self._data) 
Example 4
Project: CHATIMUSMAXIMUS   Author: benhoff   File: settings_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def index(self, row, column, parent):
        """Returns QModelIndex to row, column in parent (QModelIndex)"""
        if parent.isValid() and parent.column() != 0:
            return QtCore.QModelIndex()

        if parent.isValid():
            parent_pointer = parent.internalPointer()
            parent_dict = self.root[parent_pointer]
        else:
            parent_dict = self.root
            parent_pointer = ()
        row_key = list(parent_dict.keys())[row]
        child_pointer = (*parent_pointer, row_key)
        try:
            child_pointer = self.my_index[child_pointer]
        except KeyError:
            self.my_index[child_pointer] = child_pointer
        index = self.createIndex(row, column, child_pointer)
        return index 
Example 5
Project: CHATIMUSMAXIMUS   Author: benhoff   File: settings_model.py    License: GNU General Public License v3.0 6 votes vote down vote up
def parent(self, index):
        """
        Returns the parent (QModelIndex) of the given item (QModelIndex)
        Top level returns QModelIndex()
        """
        if not index.isValid():
            return QtCore.QModelIndex()
        child_key_list = index.internalPointer()
        if child_key_list:
            parent_key_list = child_key_list[:-1]
            if parent_key_list == ((),):
                return QtCore.QModelIndex()
            try:
                parent_key_list = self.my_index[parent_key_list]
            except KeyError:
                self.my_index[parent_key_list] = parent_key_list
            return self.createIndex(self.get_row(parent_key_list), 0,
                                    parent_key_list)

        else:
            return QtCore.QModelIndex() 
Example 6
Project: uPyLoader   Author: BetaRavener   File: main_window.py    License: MIT License 6 votes vote down vote up
def open_local_file(self, idx):
        assert isinstance(idx, QModelIndex)
        model = self.localFilesTreeView.model()
        assert isinstance(model, QFileSystemModel)

        if model.isDir(idx):
            return

        local_path = model.filePath(idx)
        remote_path = local_path.rsplit("/", 1)[1]

        if Settings().external_editor_path:
            self.open_external_editor(local_path)
        else:
            if FileInfo.is_file_binary(local_path):
                QMessageBox.information(self, "Binary file detected", "Editor doesn't support binary files.")
                return
            with open(local_path) as f:
                text = "".join(f.readlines())
                self.open_code_editor()
                self._code_editor.set_code(local_path, remote_path, text) 
Example 7
Project: KStock   Author: aseylys   File: ObjList.py    License: GNU General Public License v3.0 6 votes vote down vote up
def insertObjects(self, i, num = 1):
        if ((len(self.objects) == 0) and (self.templateObject is None)) or (num <= 0):
            return False
        i = min([max([0, i]), len(self.objects)])  # Clamp i to within [0, # of objects].
        if self.isRowObjects:
            self.beginInsertRows(QModelIndex(), i, i + num - 1)
        else:
            self.beginInsertColumns(QModelIndex(), i, i + num - 1)
        for objectIndex in range(i, i + num):
            if self.templateObject is not None:
                self.objects.insert(objectIndex, copy.deepcopy(self.templateObject))
            elif len(self.objects):
                copyIndex = min([max([0, objectIndex]), len(self.objects) - 1])  # Clamp objectIndex to a valid object index.
                self.objects.insert(objectIndex, copy.deepcopy(self.objects[copyIndex]))
        if self.isRowObjects:
            self.endInsertRows()
        else:
            self.endInsertColumns()
        return True 
Example 8
Project: KStock   Author: aseylys   File: ObjList.py    License: GNU General Public License v3.0 6 votes vote down vote up
def removeObjects(self, i, num = 1):
        if (len(self.objects) == 0) or (num <= 0):
            return False
        i = min([max([0, i]), len(self.objects) - 1])  # Clamp i to a valid object index.
        num = min([num, len(self.objects) - i])  # Clamp num to a valid number of objects.
        if num == len(self.objects):
            # Make sure we have a template for inserting objects later.
            if self.templateObject is None:
                self.templateObject = self.objects[0]
        if self.isRowObjects:
            self.beginRemoveRows(QModelIndex(), i, i + num - 1)
            del self.objects[i:i+num]
            self.endRemoveRows()
        else:
            self.beginRemoveColumns(QModelIndex(), i, i + num - 1)
            del self.objects[i:i+num]
            self.endRemoveColumns()
        return True 
Example 9
Project: dash-masternode-tool   Author: Bertrand256   File: wallet_data_models.py    License: MIT License 6 votes vote down vote up
def index(self, row, column, parent=None, *args, **kwargs):
        try:
            if not parent or not parent.isValid():
                if 0 <= row < len(self.accounts):
                    return self.createIndex(row, column, self.accounts[row])
                else:
                    return QModelIndex()
            parentNode = parent.internalPointer()
            if isinstance(parentNode, Bip44AccountType):
                addr = parentNode.address_by_index(row)
                if addr:
                    return self.createIndex(row, column, addr)
            return QModelIndex()
        except Exception as e:
            log.exception('Exception while creating index')
            raise 
Example 10
Project: ddt4all   Author: cedricp   File: ddt4all.py    License: GNU General Public License v3.0 6 votes vote down vote up
def ecuSel(self, index):
        if index.parent() == core.QModelIndex():
            return
        item = self.list.model().itemData(self.list.model().index(index.row(), 0, index.parent()))
        if qt5:
            selected = item[0]
        else:
            selected = utf8(item[0].toString())
        target = self.ecuscan.ecu_database.getTarget(selected)
        name = selected
        if target:
            self.ecuscan.addTarget(target)
            if target.addr in self.ecuscan.ecu_database.addr_group_mapping:
                group = self.ecuscan.ecu_database.addr_group_mapping[target.addr]
            else:
                group = "Unknown"
            print name, group
            name = "[ " + group + " ] " + name
        if selected:
            if name not in options.main_window.ecunamemap:
                options.main_window.ecunamemap[name] = selected
                self.treeview_ecu.addItem(name) 
Example 11
Project: kite   Author: pyrocko   File: sources_dock.py    License: GNU General Public License v3.0 6 votes vote down vote up
def __init__(self, parent, idx, *args, **kwargs):
            QtGui.QMenu.__init__(self, *args, **kwargs)
            self.parent = parent
            self.sandbox = parent.sandbox
            self.idx = idx

            def removeSource():
                self.sandbox.sources.removeSource(self.idx)

            editAction = self.addAction(
                'Edit', lambda: self.parent.editSource(self.idx))

            self.addMenu(
                SourcesAddButton.SourcesAddMenu(self.sandbox, self))
            self.addSeparator()

            removeAction = self.addAction(
                self.style().standardIcon(
                    QtGui.QStyle.SP_DialogCloseButton),
                'Remove', removeSource)

            if self.sandbox.sources.rowCount(QtCore.QModelIndex()) == 0:
                editAction.setEnabled(False)
                removeAction.setEnabled(False) 
Example 12
Project: Uranium   Author: Ultimaker   File: DefinitionTreeModel.py    License: GNU Lesser General Public License v3.0 6 votes vote down vote up
def parent(self, child):
        if not self._container:
            return QModelIndex()

        if not child.isValid():
            return QModelIndex()

        parent = child.internalPointer().parent
        if not parent:
            return QModelIndex()

        row = None
        if not parent.parent:
            row = self._container.definitions.index(parent)
        else:
            row = parent.parent.children.index(parent)

        return self.createIndex(row, 0, parent) 
Example 13
Project: dcc   Author: amimo   File: xrefwindow.py    License: Apache License 2.0 5 votes vote down vote up
def __init__(self, parent=None, win=None, xrefs=None, headers=None):
        super(XrefValueWindow, self).__init__(parent)
        self.parent = parent
        self.mainwin = win
        self.xrefs = xrefs
        self.headers = headers

        self.reverse_strings = {}

        self.proxyModel = QtCore.QSortFilterProxyModel()
        self.proxyModel.setDynamicSortFilter(True)

        self.model = QtGui.QStandardItemModel(len(self.xrefs),
                                              len(self.headers), self)

        column = 0
        for header in headers:
            self.model.setHeaderData(column, QtCore.Qt.Horizontal, header)
            column += 1

        row = 0
        for ref in xrefs:
            for column in range(len(self.headers)):
                self.model.setData(self.model.index(
                    row, column, QtCore.QModelIndex()), "%s" % ref[column])
            row += 1

        self.proxyModel.setSourceModel(self.model)

        self.setRootIsDecorated(False)
        self.setAlternatingRowColors(True)
        self.setModel(self.proxyModel)
        self.setSortingEnabled(True)
        self.setEditTriggers(QtWidgets.QAbstractItemView.NoEditTriggers)

        self.doubleClicked.connect(self.slotDoubleClicked) 
Example 14
Project: qutebrowser   Author: qutebrowser   File: test_completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def test_delete_cur_item_no_cat():
    """Test completion_item_del with no selected category."""
    callback = mock.Mock(spec=[])
    model = completionmodel.CompletionModel()
    model.rowsAboutToBeRemoved.connect(callback)
    model.rowsRemoved.connect(callback)
    with pytest.raises(qtutils.QtValueError):
        model.delete_cur_item(QModelIndex())
    callback.assert_not_called() 
Example 15
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def _cat_from_idx(self, index):
        """Return the category pointed to by the given index.

        Args:
            idx: A QModelIndex
        Returns:
            A category if the index points at one, else None
        """
        # items hold an index to the parent category in their internalPointer
        # categories have an empty internalPointer
        if index.isValid() and not index.internalPointer():
            return self._categories[index.row()]
        return None 
Example 16
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def parent(self, index):
        """Get an index to the parent of the given index.

        Override QAbstractItemModel::parent.

        Args:
            index: The QModelIndex to get the parent index for.
        """
        parent_cat = index.internalPointer()
        if not parent_cat:
            # categories have no parent
            return QModelIndex()
        row = self._categories.index(parent_cat)
        return self.createIndex(row, 0, None) 
Example 17
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def columnCount(self, parent=QModelIndex()):
        """Override QAbstractItemModel::columnCount."""
        # pylint: disable=unused-argument
        return 3 
Example 18
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def canFetchMore(self, parent):
        """Override to forward the call to the categories."""
        cat = self._cat_from_idx(parent)
        if cat:
            return cat.canFetchMore(QModelIndex())
        return False 
Example 19
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def fetchMore(self, parent):
        """Override to forward the call to the categories."""
        cat = self._cat_from_idx(parent)
        if cat:
            cat.fetchMore(QModelIndex()) 
Example 20
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def first_item(self):
        """Return the index of the first child (non-category) in the model."""
        for row, cat in enumerate(self._categories):
            if cat.rowCount() > 0:
                parent = self.index(row, 0)
                index = self.index(0, 0, parent)
                qtutils.ensure_valid(index)
                return index
        return QModelIndex() 
Example 21
Project: qutebrowser   Author: qutebrowser   File: completionmodel.py    License: GNU General Public License v3.0 5 votes vote down vote up
def last_item(self):
        """Return the index of the last child (non-category) in the model."""
        for row, cat in reversed(list(enumerate(self._categories))):
            childcount = cat.rowCount()
            if childcount > 0:
                parent = self.index(row, 0)
                index = self.index(childcount - 1, 0, parent)
                qtutils.ensure_valid(index)
                return index
        return QModelIndex() 
Example 22
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    License: GNU General Public License v2.0 5 votes vote down vote up
def columnCount(self, parent=QtCore.QModelIndex()):
                '''The number of columns for the children of the given parent.

                Args:
                    parent (:obj:`QtCore.QModelIndex`, optional): Parent

                Returns:
                    int: Number of columns
                '''
                if None == self.header:
                    return 0

                return len(self.header) 
Example 23
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    License: GNU General Public License v2.0 5 votes vote down vote up
def data(self, index, role=Qt.DisplayRole):
                '''The data stored under the given role for the item referred
                to by the index.

                Args:
                    index (:obj:`QtCore.QModelIndex`): Index
                    role (:obj:`Qt.ItemDataRole`): Default :obj:`Qt.DisplayRole`

                Returns:
                    data
                '''
                if role == Qt.DisplayRole:
                    row = self._data[index.row()]
                    if (index.column() == 0) and (type(row) != dict):
                        return row

                    elif index.column() < self.columnCount():
                        if type(row) == dict:
                            if self.header[index.column()] in row:
                                return row[self.header[index.column()]]
                            elif self.header[index.column()].lower() in row:
                                return row[self.header[index.column()].lower()]

                        return row[index.column()]

                    return None

                elif role == Qt.FontRole:
                    return QtGui.QFont().setPointSize(30)

                elif role == Qt.DecorationRole and index.column() == 0:
                    return None

                elif role == Qt.TextAlignmentRole:
                    return Qt.AlignLeft; 
Example 24
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    License: GNU General Public License v2.0 5 votes vote down vote up
def data(self, index, role):
                '''The data stored under the given role for the item referred
                to by the index.

                Args:
                    index (:obj:`QtCore.QModelIndex`): Index
                    role (:obj:`Qt.ItemDataRole`): Default :obj:`Qt.DisplayRole`

                Returns:
                    data
                '''
                if not index.isValid():
                    return None

                #   Color background
                if role == Qt.BackgroundRole:
                    metadata_id = index.data(FIRSTUI.ROLE_ID)
                    address = index.data(FIRSTUI.ROLE_ADDRESS)

                    if (metadata_id and address
                        and ((address, metadata_id) in self.ids_selected)):
                        return FIRST.color_selected

                    elif (metadata_id and address
                          and ((address, metadata_id) in self.applied_ids)):
                        return FIRST.color_applied

                    #   Data has been updated since original
                    elif not metadata_id:
                        return FIRST.color_unchanged

                    #   Return the default color
                    return FIRST.color_default

                return super(FIRST.Model.Check, self).data(index, role) 
Example 25
Project: FIRST-plugin-ida   Author: vrtadmin   File: first.py    License: GNU General Public License v2.0 5 votes vote down vote up
def drawRow(self, painter, option, index):
                '''Draws the row in the tree view that contains the model item
                index, using the painter given. The option control how the item
                is displayed.

                Args:
                    painter (:obj:`QtGui.QPainter`): Painter
                    option (:obj:`QtGui.QStyleOptionViewItem`): Options
                    index (:obj:`QtCore.QModelIndex`): Index
                '''
                metadata_id = index.data(FIRSTUI.ROLE_ID)
                header = self.header()
                firstSection = header.logicalIndex(0)
                left = header.sectionViewportPosition(firstSection)
                indent = self.__depth * self.indentation()

                if (index.data(FIRSTUI.ROLE_COMMENT)
                    and (index.row() == 0) and (index.column() == 0)):
                    lastSection = header.logicalIndex(header.count() - 1)
                    right = header.sectionViewportPosition(lastSection) + header.sectionSize(lastSection)

                    left += indent;

                    option.rect.setX(left)
                    option.rect.setWidth(right - left)

                    self.itemDelegate(index).paint(painter, option, index)

                else:
                    super(FIRST.Model.TreeView, self).drawRow(painter, option, index) 
Example 26
Project: CHATIMUSMAXIMUS   Author: benhoff   File: settings_model.py    License: GNU General Public License v3.0 5 votes vote down vote up
def rowCount(self, parent):
        """Returns number of rows in parent (QModelIndex)"""
        if parent.column() > 0:
            return 0    # only keys have children, not values
        if parent.isValid():
            indexPtr = parent.internalPointer()
            parentValue = self.root[indexPtr]
            if isinstance(parentValue, OrderedDict):
                return len(self.root[indexPtr])
            else:
                return 0
        else:
            return len(self.root) 
Example 27
Project: CHATIMUSMAXIMUS   Author: benhoff   File: settings_model.py    License: GNU General Public License v3.0 5 votes vote down vote up
def data(self, index, role):
        """Returns data for given role for given index (QModelIndex)"""
        if not index.isValid():
            return None

        if role != Qt.DisplayRole and role != Qt.EditRole:
            return None

        indexPtr = index.internalPointer()
        if index.column() == 1:    # Column 1, send the value
            return self.root[indexPtr]
        else:                   # Column 0, send the key
            return indexPtr[-1] 
Example 28
Project: uPyLoader   Author: BetaRavener   File: main_window.py    License: MIT License 5 votes vote down vote up
def execute_mcu_code(self):
        idx = self.mcuFilesListView.currentIndex()
        assert isinstance(idx, QModelIndex)
        model = self.mcuFilesListView.model()
        assert isinstance(model, QStringListModel)
        file_name = model.data(idx, Qt.EditRole)
        self._connection.run_file(file_name) 
Example 29
Project: uPyLoader   Author: BetaRavener   File: main_window.py    License: MIT License 5 votes vote down vote up
def remove_file(self):
        idx = self.mcuFilesListView.currentIndex()
        assert isinstance(idx, QModelIndex)
        model = self.mcuFilesListView.model()
        assert isinstance(model, QStringListModel)
        file_name = model.data(idx, Qt.EditRole)
        try:
            self._connection.remove_file(file_name)
        except OperationError:
            QMessageBox().critical(self, "Operation failed", "Could not remove the file.", QMessageBox.Ok)
            return
        self.list_mcu_files() 
Example 30
Project: uPyLoader   Author: BetaRavener   File: main_window.py    License: MIT License 5 votes vote down vote up
def mcu_file_selection_changed(self):
        idx = self.mcuFilesListView.currentIndex()
        assert isinstance(idx, QModelIndex)
        if idx.row() >= 0:
            self.executeButton.setEnabled(True)
            self.removeButton.setEnabled(True)
            self.transferToPcButton.setEnabled(True)
        else:
            self.executeButton.setEnabled(False)
            self.removeButton.setEnabled(False)
            self.transferToPcButton.setEnabled(False)