Python源码示例:PyQt5.QtCore.Qt.EditRole()

示例1
def setModelData(self, editor, model, index):
        ''' 
        Set model data to current choice (if choice is a key, set data to its associated value).
        '''
        try:
            choice = self.choices[editor.currentIndex()]
            if (type(choice) is tuple) and (len(choice) == 2):
                # choice is a (key, value) tuple.
                key, val = choice
                value = copy.deepcopy(val)  # Deepcopy of val in case it is a complex object.
            else:
                # choice is a value.
                value = choice
            model.setData(index, value, Qt.EditRole)
            index.model().dataChanged.emit(index, index)  # Tell model to update cell display.
        except:
            pass 
示例2
def data(self, index, role = Qt.DisplayRole):
        if not index.isValid():
            return None
        obj = self.getObject(index)
        prop = self.getProperty(index)
        if role == Qt.BackgroundRole:
            return color(obj.D)
        if role == Qt.TextAlignmentRole:
            return Qt.AlignCenter
        if (obj is None) or (prop is None):
            return None
        try:
            if role in [Qt.DisplayRole, Qt.EditRole]:
                return getAttrRecursive(obj, prop['attr'])
        except:
            return None
        return None 
示例3
def setData(self, index, value, role = Qt.EditRole):
        if not index.isValid():
            return False
        obj = self.getObject(index)
        prop = self.getProperty(index)
        if (obj is None) or (prop is None):
            return None
        try:
            action = prop.get('action', None)
            if action is not None:
                if action == "button":
                    getAttrRecursive(obj, prop['attr'])()  # Call obj.attr()
                    return True
                elif action == "fileDialog":
                    pass  # File loading handled via @property.setter obj.attr below. Otherwise just sets the file name text.
            if role == Qt.EditRole:
                if type(value) == QVariant:
                    value = value.toPyObject()
                if (QT_VERSION_STR[0] == '4') and (type(value) == QString):
                    value = str(value)
                setAttrRecursive(obj, prop['attr'], value)
                return True
        except:
            return False
        return False 
示例4
def editorEvent(self, event, model, option, index):
        ''' 
        Handle mouse events in cell.
        On left button release in this cell, call model's setData() method,
            wherein the button clicked action should be handled.
        Currently, the value supplied to setData() is the button text, but this is arbitrary.
        '''
        if event.button() == Qt.LeftButton:
            if event.type() == QEvent.MouseButtonPress:
                if option.rect.contains(event.pos()):
                    self._isMousePressed = True
                    return True
            elif event.type() == QEvent.MouseButtonRelease:
                self._isMousePressed = False
                if option.rect.contains(event.pos()):
                    model.setData(index, self.text, Qt.EditRole)  # Model should handle button click action in its setData() method.
                    return True
        return False 
示例5
def data(self, index, role=None):
        if index.isValid():
            data = index.internalPointer()
            col = index.column()
            if data:
                if role in (Qt.DisplayRole, Qt.EditRole):
                    if col == 0:
                        # if isinstance(data, Bip44AccountType):
                        #     return data.get_account_name()
                        # else:
                        #     return f'/{data.address_index}: {data.address}'
                        return data
                    elif col == 1:
                        b = data.balance
                        if b:
                            b = b/1e8
                        return b
                    elif col == 2:
                        b = data.received
                        if b:
                            b = b/1e8
                        return b
        return QVariant() 
示例6
def __lt__(self, other):
        if ( isinstance(other, QTableWidgetItem) ):
            try:
                my_value = int(self.data(Qt.EditRole))
            except:
                # This will throw an exception if a channel is say "3+5" for multiple channels
                # Break it down and sort it on the first channel #
                cellData = str(self.data(Qt.EditRole))
                firstChannel = cellData.split('+')[0]
                my_value = int(firstChannel)
                
            try:
                other_value = int(other.data(Qt.EditRole))
            except:
                # This will throw an exception if a channel is say "3+5" for multiple channels
                # Break it down and sort it on the first channel #
                cellData = str(self.data(Qt.EditRole))
                firstChannel = cellData.split('+')[0]
                other_value = int(firstChannel)

            return my_value < other_value

        return super(IntTableWidgetItem, self).__lt__(other) 
示例7
def __lt__(self, other):
        if ( isinstance(other, QTableWidgetItem) ):
            try:
                my_value = float(self.data(Qt.EditRole))
            except:
                my_value = 0.0
                
            try:
                other_value = float(other.data(Qt.EditRole))
            except:
                other_value = 0.0

            return my_value < other_value

        return super(FloatTableWidgetItem, self).__lt__(other)

# ------------------  Table Sorting by Timestamp Class  ------------------------------ 
示例8
def setData(self, index, value, role=None):
        if not index.isValid():
            return False
        if role == Qt.EditRole:
            node = index.internalPointer()
            try:
                value = int(value)
            except (ValueError, TypeError):
                return False
            if index.column() == 1:
                node.capacity = value
                self.dataChanged.emit(index, index)
                return True
            elif index.column() == 2:
                node.recoil = value
                self.dataChanged.emit(index, index)
                return True
            elif index.column() == 3:
                node.reload = value
                return True
                self.dataChanged.emit(index, index)
        return False 
示例9
def data(self, qindex:QModelIndex, role=None):
        if role == Qt.DisplayRole or role == Qt.EditRole:
            entry = self.entries[qindex.row()]
            attr = self.columns[qindex.column()]
            value = getattr(entry, attr)
            if attr in ("gmd_name_index", "gmd_description_index"):
                return get_t9n(self.model, "t9n", value)
            elif attr == "kire_id":
                kire_model = self.model.get_relation_data("kire")
                if kire_model is None:
                    return None
                else:
                    return kire_model.entries[value]
            return value
        elif role == Qt.UserRole:
            entry = self.entries[qindex.row()]
            return entry 
示例10
def data(self, index, role):
        root = self.get_root_object()
        if role == Qt.DisplayRole or role == Qt.EditRole:
            r = index.row()
            c = index.column()
            eval_str = ('root' + self.colEvalStr[c]).format(r)
            try:
                val = eval(eval_str)
                valStr = self.colFormats[c].format(val)
                return valStr
            except IndexError:
                return ''
            except TypeError:
                print('Data type error: ', eval_str, val)
                return ''
        else:
            return None 
示例11
def data(self, index, role):
        if not index.isValid():
            return None
        if index.column() == 0:
            value = ('' if self.my_data[index.row()][index.column() + 1]
                     else 'Skip')
        else:
            value = self.my_data[index.row()][index.column() + 1]
        if role == Qt.EditRole:
            return value
        elif role == Qt.DisplayRole:
            return value
        elif role == Qt.CheckStateRole:
            if index.column() == 0:
                return (
                    Qt.Checked if self.my_data[index.row()][index.column() + 1]
                    else Qt.Unchecked) 
示例12
def data(self, index, rola=Qt.DisplayRole):
        """ Wyświetlanie danych """
        i = index.row()
        j = index.column()

        if rola == Qt.DisplayRole:
            return '{0}'.format(self.tabela[i][j])
        elif rola == Qt.CheckStateRole and (j == 3 or j == 4):
            if self.tabela[i][j]:
                return Qt.Checked
            else:
                return Qt.Unchecked
        elif rola == Qt.EditRole and j == 1:
            return self.tabela[i][j]
        else:
            return QVariant() 
示例13
def data(self, index, rola=Qt.DisplayRole):
        """ Wyświetlanie danych """
        i = index.row()
        j = index.column()

        if rola == Qt.DisplayRole:
            return '{0}'.format(self.tabela[i][j])
        elif rola == Qt.CheckStateRole and (j == 3 or j == 4):
            if self.tabela[i][j]:
                return Qt.Checked
            else:
                return Qt.Unchecked
        elif rola == Qt.EditRole and j == 1:
            return self.tabela[i][j]
        else:
            return QVariant() 
示例14
def setData(self, index: QModelIndex, value, role=None):
        if role == Qt.EditRole:
            i, j = index.row(), index.column()
            fieldtype = self.field_types[i]
            try:
                if j == 0:
                    present_captions = {ft.caption for ft in self.field_types}
                    if value not in present_captions:
                        fieldtype.caption = value
                elif j == 1:
                    try:
                        fieldtype.function = FieldType.Function[value]
                    except KeyError:
                        return False
                if j == 2:
                    fieldtype.display_format_index = int(value)
            except ValueError:
                return False

            return True 
示例15
def setData(self, index: QModelIndex, value, role=None):
        row = index.row()
        lbl = self.display_labels[row]
        if role == Qt.EditRole and index.column() in (0, 1, 2, 3):
            if index.column() == 0:
                lbl.name = value
                new_field_type = self.controller.field_types_by_caption.get(value, None)
                self.controller.active_message_type.change_field_type_of_label(lbl, new_field_type)
            elif index.column() == 1:
                lbl.color_index = value
                self.label_color_changed.emit(lbl)
            elif index.column() == 2:
                lbl.display_format_index = value
            elif index.column() == 3:
                lbl.display_order_str = value

            self.dataChanged.emit(self.index(row, 0),
                                  self.index(row, self.columnCount()))
        elif role == Qt.CheckStateRole and index.column() == 0:
            lbl.show = value
            self.protolabel_visibility_changed.emit(lbl)
            return True 
示例16
def setData(self, index: QModelIndex, value, role=None):
        if role == Qt.EditRole:
            i, j = index.row(), index.column()
            rule = self.ruleset[i]
            try:
                if j == 0:
                    rule.start = int(value) - 1
                elif j == 1:
                    rule.end = int(value)
                if j == 2:
                    rule.value_type = int(value)
                if j == 3:
                    rule.operator_description = self.operator_descriptions[int(value)]
                if j == 4:
                    rule.target_value = value
            except ValueError:
                return False

            return True 
示例17
def data(self, index, role=Qt.DisplayRole):
        row = index.row()
        if not index.isValid() or row >= len(self.message_types):
            return

        message_type = self.message_types[row]

        if role == Qt.DisplayRole:
            if index.column() == 0:
                return message_type.name
            elif index.column() == 1:
                return ""
        elif role == Qt.CheckStateRole:
            if index.column() == 0:
                return message_type.show
            elif index.column() == 1:
                return None
        elif role == Qt.EditRole:
            if index.column() == 0:
                return message_type.name
        elif role == Qt.FontRole and index.column() == 0:
            font = QFont()
            font.setBold(index.row() in self.selected_message_type_indices)
            return font 
示例18
def test_label_tooltip(self):
        self.cfc.ui.cbProtoView.setCurrentIndex(0)
        self.cfc.add_protocol_label(0, 16, 2, 0, edit_label_name=False)
        model = self.cfc.label_value_model
        model.setData(model.index(0, 0), "test", Qt.EditRole)
        table_model = self.cfc.protocol_model
        for i in range(0, 16):
            self.assertEqual(table_model.data(table_model.index(2, i), Qt.ToolTipRole), "test", msg=str(i))

        for i in range(17, 100):
            self.assertEqual(table_model.data(table_model.index(2, i), Qt.ToolTipRole), "", msg=str(i))

        self.cfc.add_protocol_label(20, 24, 2, 0, edit_label_name=False)
        checksum_field_type = next(ft for ft in self.cfc.field_types if ft.function == FieldType.Function.CHECKSUM)
        model.setData(model.index(1, 0), checksum_field_type.caption, Qt.EditRole)
        for i in range(20, 24):
            self.assertIn("Expected", table_model.data(table_model.index(2, i), Qt.ToolTipRole))

        for i in range(0, 20):
            self.assertNotIn("Expected", table_model.data(table_model.index(2, i), Qt.ToolTipRole)) 
示例19
def data(self, index, role=None):
        value = self._anchor_positions[index.row()][index.column()]
        if index.isValid():
            if index.column() == 0:
                if role == Qt.CheckStateRole:
                    return QVariant(value)
            elif index.column() == 1:
                if role == Qt.DisplayRole:
                    return QVariant(value)
            else:
                if role == Qt.DisplayRole:
                    return QVariant('%.2f' % (value))
                elif role == Qt.EditRole:
                    return QVariant(value)
                elif role == Qt.BackgroundRole:
                    return self._get_background(index.row(), index.column())

        return QVariant() 
示例20
def add_items(self):
        if self.feature_dict:
            for key in self.feature_dict.keys():
                root = QTreeWidgetItem(self, [key])

                for type_t in self.feature_dict[key]:
                    feature = QTreeWidgetItem(root, ['Feature Types'])
                    feature.setData(0, Qt.EditRole, type_t)
                    feature.setCheckState(1, Qt.Unchecked)
        self.resizeColumnToContents(0)
        self.resizeColumnToContents(1)
        self.is_ready = True
        self.expandAll() 
示例21
def __set_item_widget(widget, col, item, key):
        widget.setData(col, Qt.EditRole, item[key].title()) 
示例22
def setData(self, index, value, role=Qt.EditRole):
        pointer = self.my_index[index.internalPointer()]
        self.root[pointer] = value
        self.dataChanged.emit(index, index)
        return True 
示例23
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] 
示例24
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) 
示例25
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() 
示例26
def read_mcu_file(self, idx):
        assert isinstance(idx, QModelIndex)
        model = self.mcuFilesListView.model()
        assert isinstance(model, QStringListModel)
        file_name = model.data(idx, Qt.EditRole)

        progress_dlg = FileTransferDialog(FileTransferDialog.DOWNLOAD)
        progress_dlg.finished.connect(lambda: self.finished_read_mcu_file(file_name, progress_dlg.transfer))
        progress_dlg.show()
        self._connection.read_file(file_name, progress_dlg.transfer) 
示例27
def transfer_to_pc(self):
        idx = self.mcuFilesListView.currentIndex()
        assert isinstance(idx, QModelIndex)
        model = self.mcuFilesListView.model()
        assert isinstance(model, QStringListModel)
        remote_path = model.data(idx, Qt.EditRole)
        local_path = self.localPathEdit.text() + "/" + remote_path

        progress_dlg = FileTransferDialog(FileTransferDialog.DOWNLOAD)
        progress_dlg.finished.connect(lambda: self.finished_transfer_to_pc(local_path, progress_dlg.transfer))
        progress_dlg.show()
        self._connection.read_file(remote_path, progress_dlg.transfer) 
示例28
def setModelData(self, editor, model, index):
        ''' 
        Cast the QLineEdit text to a float value, and update the model with this value.
        '''
        try:
            value = float(editor.text())
            model.setData(index, value, Qt.EditRole)
        except:
            pass  # If we can't cast the user's input to a float, don't do anything. 
示例29
def createEditor(self, parent, option, index):
        ''' 
        Instead of creating an editor, just popup a modal file dialog
        and set the model data to the selected file name, if any.
        '''
        pathToFileName = ""
        if QT_VERSION_STR[0] == '4':
            pathToFileName = QFileDialog.getOpenFileName(None, "Open")
        elif QT_VERSION_STR[0] == '5':
            pathToFileName, temp = QFileDialog.getOpenFileName(None, "Open")
        pathToFileName = str(pathToFileName)  # QString ==> str
        if len(pathToFileName):
            index.model().setData(index, pathToFileName, Qt.EditRole)
            index.model().dataChanged.emit(index, index)  # Tell model to update cell display.
        return None 
示例30
def setModelData(self, editor, model, index):
        ''' 
        Toggle the boolean state in the model.
        '''
        checked = not bool(index.model().data(index, Qt.DisplayRole))
        model.setData(index, checked, Qt.EditRole)