我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用PyQt5.QtCore.Qt.DisplayRole()。
def test_data(self): # Edit is performed using the raw data key_items = [] val_items = [] for key, val in self.props.items(): key_items.append(PropertyItem(key)) val_items.append(PropertyItem(val)) for idx in range(len(key_items)): # default role should return string name = key_items[idx].data(role=Qt.DisplayRole) self.assertIsInstance(name, str) data_string = val_items[idx].data(role=Qt.DisplayRole) self.assertIsInstance(data_string, str) self.assertEqual(data_string, str(self.props[name])) # Data should be available in raw format using special role data = val_items[idx].data(role=PropertyItem.RawDataRole) self.assertEqual(self.props[name], data)
def test_setData(self): # only if the returned string can be parsed it should be accepted item = PropertyItem(self.props["List"]) edit_str = item.data(role=Qt.EditRole) self.assertIsInstance(edit_str, str) self.assertEqual(edit_str, str(self.props["List"])) new_list = [1, 3, 5] item.setData(new_list, role=PropertyItem.RawDataRole) self.assertEqual(item.data(role=PropertyItem.RawDataRole), new_list) new_str = str(new_list) self.assertEqual(item.data(role=Qt.DisplayRole), new_str) # invalid data should be rejected and exception should be printed to log item.setData(edit_str[:-1], role=Qt.EditRole) self.assertEqual(item.data(role=Qt.DisplayRole), new_str)
def data(self, index, role=None): if role == Qt.DisplayRole: # start = time.time() # answer = str(index.row()) + ' ' + str(index.column()) answer = '' try: # answer = self.get_participation_data(index.row())[index.column()] row = index.row() column = index.column() answer = self.cache[row][column] except Exception as e: logging.exception(str(e)) # end = time.time() # logging.debug('Data() ' + str(index.row()) + ' ' + str(index.column()) + ': ' + str(end - start) + ' s') return QVariant(answer) return QVariant()
def setData(self, index, value, role): """Set the role data for the item at index to value.""" if not index.isValid(): return False node = self.getNode(index) column = index.column() if role == Qt.DisplayRole or role == Qt.EditRole: if column > 0 and not node.childCount(): try: node.setItemData(column, float(value)) except ValueError: return False else: node.setItemData(column, value) elif role == Qt.CheckStateRole: node.setCheckState(value) if value == Qt.Checked: self.nodeCheckStateChanged.emit(index) self.dataChanged.emit(index, index) return True
def data(self, role): if role in (Qt.EditRole, Qt.StatusTipRole): return self.formula() if role == Qt.DisplayRole: return self.display() t = str(self.display()) try: number = int(t) except ValueError: number = None if role == Qt.TextColorRole: if number is None: return QColor(Qt.black) elif number < 0: return QColor(Qt.red) return QColor(Qt.blue) if role == Qt.TextAlignmentRole: if t and (t[0].isdigit() or t[0] == '-'): return Qt.AlignRight | Qt.AlignVCenter return super(SpreadSheetItem, self).data(role)
def setModelData(self, editor, model, idx): data_idx = idx.sibling(idx.row(), 0) ref = model.data(data_idx, Qt.UserRole) self._widget.do_remove_ref(ref, check=False) if idx.column() == 0: ref.ReferenceTypeId = editor.get_node().nodeid model.setData(idx, ref.ReferenceTypeId.to_string(), Qt.DisplayRole) elif idx.column() == 1: ref.NodeId = editor.get_node().nodeid ref.NodeClass = editor.get_node().get_node_class() model.setData(idx, ref.NodeId.to_string(), Qt.DisplayRole) model.setData(data_idx, ref, Qt.UserRole) if ref.NodeId.is_null() or ref.ReferenceTypeId.is_null(): logger.info("Do not save yet. Need NodeId and ReferenceTypeId to be set") return self._write_ref(ref)
def expand_to_node(self, node): """ Expand tree until given node and select it """ if isinstance(node, str): idxlist = self.model.match(self.model.index(0, 0), Qt.DisplayRole, node, 1, Qt.MatchExactly|Qt.MatchRecursive) node = self.model.data(idxlist[0], Qt.UserRole) path = node.get_path() for node in path: # FIXME: this would be the correct way if it would work #idxlist = self.model.match(self.model.index(0, 0), Qt.UserRole, QVariantnode, 2, Qt.MatchExactly|Qt.MatchRecursive) try: text = node.get_display_name().Text except UaError as ex: return idxlist = self.model.match(self.model.index(0, 0), Qt.DisplayRole, text, 1, Qt.MatchExactly|Qt.MatchRecursive) if idxlist: idx = idxlist[0] self.view.setExpanded(idx, True) self.view.setCurrentIndex(idx) self.view.activated.emit(idx)
def data(self, index: QModelIndex, role=None): row = index.row() if role == Qt.DisplayRole: if row == 0: return "not assigned" else: try: return self.participants[row-1].name + " ("+ self.participants[row-1].shortname + ")" except IndexError: return None elif role == Qt.CheckStateRole: if row == 0: return Qt.Checked if self.show_unassigned else Qt.Unchecked else: try: return Qt.Checked if self.participants[row-1].show else Qt.Unchecked except IndexError: return None
def data(self, index, role=Qt.DisplayRole): row = index.row() if row >= len(self.message_type): return label = self.message_type[row] if role == Qt.DisplayRole: return label.name elif role == Qt.CheckStateRole: return label.show elif role == Qt.BackgroundColorRole: return constants.LABEL_COLORS[label.color_index] elif role == Qt.FontRole: font = QFont() font.setItalic(label.field_type is None) return font
def data(self, index: QModelIndex, role=Qt.DisplayRole): if not index.isValid(): return None if role == Qt.DisplayRole: i = index.row() j = index.column() rule = self.ruleset[i] assert isinstance(rule, Rule) if j == 0: return rule.start + 1 elif j == 1: return rule.end elif j == 2: return rule.value_type elif j == 3: return rule.operator_description elif j == 4: return rule.target_value
def setData(self, index: QModelIndex, value, role=Qt.DisplayRole): i = index.row() j = index.column() if i >= len(self.participants): return False participant = self.participants[i] if j == 0: participant.name = value elif j == 1: participant.shortname = value elif j == 2: participant.color_index = int(value) elif j == 3: for other in self.participants: if other.relative_rssi == int(value): other.relative_rssi = participant.relative_rssi break participant.relative_rssi = int(value) self.participant_rssi_edited.emit() elif j == 4: participant.address_hex = value return True
def headerData(self, section, orientation, role=Qt.DisplayRole): '''The data for the given role and section in the header with the specified orientation. Args: section (:obj:`int`): orientation (:obj:`Qt.Orientation`): role (:obj:`Qt.DisplayRole`): Returns: data ''' if role != Qt.DisplayRole: return None if (orientation == Qt.Horizontal) and (section < len(self.header)): return self.header[section] return None
def data(self, index, role): if role == Qt.DisplayRole: row = index.row() col = index.column() if col == 0: return QVariant(self._mp_database.db[row].name) elif col == 1: return QVariant(self._mp_database.db[row].state) return QVariant()
def headerData(self, section, orientation, role): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: return QVariant(self._mp_table_header[section]) return QVariant()
def data(self, index, role): if role == Qt.DisplayRole: row = index.row() col = index.column() return QVariant(self._flight_data[row][col]) return QVariant()
def headerData(self, section, orientation, role): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: return QVariant(self._flight_data_header[section])
def __init__(self, parent, info, title="Channel Properties"): super().__init__(parent) self.setWindowTitle(title) self.model = QStandardItemModel(info["nchan"], 4) self.model.setHorizontalHeaderLabels(["#", "Label", "Type", "Bad"]) for index, ch in enumerate(info["chs"]): item = QStandardItem() item.setData(index, Qt.DisplayRole) item.setFlags(item.flags() & ~Qt.ItemIsEditable) self.model.setItem(index, 0, item) self.model.setItem(index, 1, QStandardItem(ch["ch_name"])) kind = channel_type(info, index).upper() self.model.setItem(index, 2, QStandardItem(str(kind))) bad = QStandardItem() bad.setData(ch["ch_name"] in info["bads"], Qt.UserRole) bad.setCheckable(True) bad.setEditable(False) checked = ch["ch_name"] in info["bads"] bad.setCheckState(Qt.Checked if checked else Qt.Unchecked) self.model.setItem(index, 3, bad) self.model.itemChanged.connect(bad_changed) self.proxymodel = MySortFilterProxyModel() self.proxymodel.setSourceModel(self.model) self.view = QTableView() self.view.setModel(self.proxymodel) self.view.setItemDelegateForColumn(2, ComboBoxDelegate(self.view)) self.view.setEditTriggers(QAbstractItemView.AllEditTriggers) self.view.verticalHeader().setVisible(False) self.view.horizontalHeader().setStretchLastSection(True) self.view.setShowGrid(False) self.view.setSelectionMode(QAbstractItemView.NoSelection) self.view.setSortingEnabled(True) self.view.sortByColumn(0, Qt.AscendingOrder) self.view.resizeColumnsToContents() # for i in range(self.model.rowCount()): # self.view.openPersistentEditor(self.model.index(i, 2)) vbox = QVBoxLayout(self) vbox.addWidget(self.view) self.buttonbox = QDialogButtonBox(QDialogButtonBox.Ok | QDialogButtonBox.Cancel) vbox.addWidget(self.buttonbox) self.buttonbox.accepted.connect(self.accept) self.buttonbox.rejected.connect(self.reject) self.resize(400, 650)
def model_updated(self, model): config = model.get_config() map_names = config.maps_to_show with blocked_signals(self.selectedMap): current_selected = self.selectedMap.currentData(Qt.UserRole) self.selectedMap.clear() self.selectedMap.addItems(map_names) for index, map_name in enumerate(map_names): self.selectedMap.setItemData(index, map_name, Qt.UserRole) if map_name in config.map_plot_options and config.map_plot_options[map_name].title: title = config.map_plot_options[map_name].title self.selectedMap.setItemData(index, map_name + ' (' + title + ')', Qt.DisplayRole) for ind in range(self.selectedMap.count()): if self.selectedMap.itemData(ind, Qt.UserRole) == current_selected: self.selectedMap.setCurrentIndex(ind) break if self.selectedMap.count(): self._update_map_specifics(self.selectedMap.currentData(Qt.UserRole)) else: self._update_map_specifics(None)
def paint(self, painter: QPainter, option: QStyleOptionViewItem, index: QModelIndex) -> None: r = option.rect pencolor = Qt.white if self.theme == 'dark' else Qt.black if self.parent.isEnabled(): if option.state & QStyle.State_Selected: painter.setBrush(QColor(150, 190, 78, 150)) elif option.state & QStyle.State_MouseOver: painter.setBrush(QColor(227, 212, 232)) pencolor = Qt.black else: brushcolor = QColor(79, 85, 87, 175) if self.theme == 'dark' else QColor('#EFF0F1') painter.setBrush(Qt.transparent if index.row() % 2 == 0 else brushcolor) painter.setPen(Qt.NoPen) painter.drawRect(r) thumb = QIcon(index.data(Qt.DecorationRole + 1)) starttime = index.data(Qt.DisplayRole + 1) endtime = index.data(Qt.UserRole + 1) externalPath = index.data(Qt.UserRole + 2) r = option.rect.adjusted(5, 0, 0, 0) thumb.paint(painter, r, Qt.AlignVCenter | Qt.AlignLeft) painter.setPen(QPen(pencolor, 1, Qt.SolidLine)) r = option.rect.adjusted(110, 8, 0, 0) painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold)) painter.drawText(r, Qt.AlignLeft, 'FILENAME' if len(externalPath) else 'START') r = option.rect.adjusted(110, 20, 0, 0) painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal)) if len(externalPath): painter.drawText(r, Qt.AlignLeft, self.clipText(os.path.basename(externalPath), painter)) else: painter.drawText(r, Qt.AlignLeft, starttime) if len(endtime) > 0: r = option.rect.adjusted(110, 45, 0, 0) painter.setFont(QFont('Noto Sans UI', 10 if sys.platform == 'darwin' else 8, QFont.Bold)) painter.drawText(r, Qt.AlignLeft, 'RUNTIME' if len(externalPath) else 'END') r = option.rect.adjusted(110, 60, 0, 0) painter.setFont(QFont('Noto Sans UI', 11 if sys.platform == 'darwin' else 9, QFont.Normal)) painter.drawText(r, Qt.AlignLeft, endtime) if self.parent.verticalScrollBar().isVisible(): self.parent.setFixedWidth(210) else: self.parent.setFixedWidth(190)
def headerData(self, section, orientation, role): if role == Qt.DisplayRole and orientation==Qt.Horizontal: return keywordNameMap[self.seriesColumns[section]]
def data(self, index, role): if index.isValid() and role == Qt.DisplayRole: return str(self.seriesTable[index.row()][index.column()])
def data(self, QModelIndex, int_role=None): if not QModelIndex.isValid(): return QVariant() if int_role == Qt.BackgroundColorRole: if QModelIndex.row() * self.column_count + QModelIndex.column() in self.breakpoint_list: return QVariant(QColor(Qt.red)) elif int_role != Qt.DisplayRole: return QVariant() if self.data_array is None: return QVariant() return QVariant(self.data_array[QModelIndex.row() * self.column_count + QModelIndex.column()])
def data(self, QModelIndex, int_role=None): if not QModelIndex.isValid(): return QVariant() if int_role == Qt.BackgroundColorRole: if QModelIndex.row() * self.column_count + QModelIndex.column() in self.breakpoint_list: return QVariant(QColor(Qt.red)) elif int_role != Qt.DisplayRole: return QVariant() if self.data_array is None: return QVariant() return QVariant( SysUtils.aob_to_str(self.data_array[QModelIndex.row() * self.column_count + QModelIndex.column()]))
def headerData(self, section, orientation, role=None): if role == Qt.DisplayRole: return QVariant() if orientation == Qt.Horizontal: if section%2==0: return "x" else: return "y" else: return "{}".format(section+1)
def data(self, index, role=None): if role == Qt.DisplayRole: return self.m_data[index.row()][index.column()] elif role == Qt.EditRole: return self.m_data[index.row()][index.column()] elif role == Qt.BackgroundRole: for color, rect in self.m_mapping.items(): if rect.contains(index.column(), index.row()): return QColor(color) return QVariant()
def headerData(self, section, orientation, role=None): print(orientation) if role == Qt.DisplayRole: return QVariant() if orientation == Qt.Horizontal: if section%2==0: return "x" else: return "y" else: return "{}".format(section+1)
def data(self, index, role=Qt.DisplayRole): if index.isValid() and role in (Qt.DisplayRole, Qt.EditRole): row, column = index.row(), index.column() return self._data(row, column) return None
def setData(self, index, value, role=Qt.EditRole): if index.isValid() and role in (Qt.DisplayRole, Qt.EditRole): row, column = index.row(), index.column() oldValue = self._data(row, column) self._setData(row, column, value) if not self._inDrop: self.valueChanged.emit(index, oldValue, value) self.dataChanged.emit(index, index, [role]) return True return super(AbstractListModel, self).setData(index, value, role)
def headerData(self, section, orientation, role=Qt.DisplayRole): if role == Qt.DisplayRole and orientation == Qt.Horizontal: if section >= len(self._headerLabels): return None else: return self._headerLabels[section] return super(AbstractListModel, self).headerData(section, orientation, role)
def paint(self, painter, option, index): super().paint(painter, option, index) data = index.data(Qt.DisplayRole) if isinstance(data, QColor): rect = option.rect.adjusted(2, 1, -2, -1) if data.isValid(): painter.fillRect(rect, data) else: backgroundColor = QColor(214, 214, 214) color = QColor(170, 170, 170) tileSize = round(rect.height() / 3) drawing.drawTiles( painter, rect, tileSize=tileSize, color=color, backgroundColor=backgroundColor)
def headerData(self, index, orientation, role=None): if role == Qt.DisplayRole: if orientation == Qt.Horizontal: columns = self.get_headers() return _(columns[index]) if orientation == Qt.Vertical: return str(index+1)
def filterAcceptsRow(self, row, index): if not self.filter_applied: return True try: source_model = self.sourceModel() size = source_model.columnCount() for i in range(size): if self.filter_map is not None and self.filter_map[i] is not None and self.filter_map[i] != '': filter_string = self.filter_map[i] cell = source_model.data(source_model.index(row, i), Qt.DisplayRole) if str(cell.value()).find(filter_string) == -1: return False except Exception as e: logging.exception(str(e)) return True
def data(self, index, role): """Return role specific data for the item referred by the index.""" if not index.isValid(): return if role == Qt.DisplayRole or role == Qt.EditRole: label = self.data[index.row()].label return label
def data(self, index, role): """Return role specific data for the item referred by index.column().""" if not index.isValid(): pass node = self.getNode(index) column = index.column() value = node.getItemData(column) if role == Qt.DisplayRole: try: if column == 1: return '{0:8.3f}'.format(value) else: return '{0:8.2f}'.format(value) except ValueError: return value if role == Qt.EditRole: return str(value) if role == Qt.CheckStateRole: if node.parent == self.rootNode and column == 0: return node.getCheckState() if role == Qt.TextAlignmentRole: if column > 0: return Qt.AlignRight
def headerData(self, section, orientation, role): """Return the data for the given role and section in the header with the specified orientation. """ if orientation == Qt.Horizontal and role == Qt.DisplayRole: return self.header[section]
def data(self, index, role): if not index.isValid(): return None if role != Qt.DisplayRole: return None item = index.internalPointer() return item.data(index.column())
def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole: return self.rootItem.data(section) return None
def data(self, index, role): if not index.isValid(): return None if role != Qt.DisplayRole: return None item = index.internalPointer() node = item.node() attributes = [] attributeMap = node.attributes() if index.column() == 0: return node.nodeName() elif index.column() == 1: for i in range(0, attributeMap.count()): attribute = attributeMap.item(i) attributes.append(attribute.nodeName() + '="' + attribute.nodeValue() + '"') return " ".join(attributes) if index.column() == 2: value = node.nodeValue() if value is None: return '' return ' '.join(node.nodeValue().split('\n')) return None
def headerData(self, section, orientation, role): if orientation == Qt.Horizontal and role == Qt.DisplayRole: if section == 0: return "Name" if section == 1: return "Attributes" if section == 2: return "Value" return None
def createGUI(self): tableData = [ ("Alice", QColor('aliceblue')), ("Neptun", QColor('aquamarine')), ("Ferdinand", QColor('springgreen')) ] table = QTableWidget(3, 2) table.setHorizontalHeaderLabels(["Name", "Hair Color"]) table.verticalHeader().setVisible(False) table.resize(150, 50) for i, (name, color) in enumerate(tableData): nameItem = QTableWidgetItem(name) colorItem = QTableWidgetItem() colorItem.setData(Qt.DisplayRole, color) table.setItem(i, 0, nameItem) table.setItem(i, 1, colorItem) table.resizeColumnToContents(0) table.horizontalHeader().setStretchLastSection(True) layout = QGridLayout() layout.addWidget(table, 0, 0) self.setLayout(layout) self.setWindowTitle("Color Editor Factory")
def data(self, index, role=Qt.DisplayRole): try: animal = self._animals[index.row()] except IndexError: return QVariant() if role == self.TypeRole: return animal.type() if role == self.SizeRole: return animal.size() return QVariant()
def orderItems(self): orderList = [] for row in range(len(self.items)): text = self.itemsTable.item(row, 0).text() quantity = int(self.itemsTable.item(row, 1).data(Qt.DisplayRole)) orderList.append((text, max(0, quantity))) return orderList
def data(self, index, role): value = super(CustomSqlModel, self).data(index, role) if value is not None and role == Qt.DisplayRole: if index.column() == 0: return '#%d' % value elif index.column() == 2: return value.upper() if role == Qt.TextColorRole and index.column() == 1: return QColor(Qt.blue) return value