Я создаю подкласс QStyledItemDelegate, чтобы отображать раскрывающийся список QCombobox в QTableView. Делегат определяет тип данных из модели таблицы, и если dataType == EnumMeta, отображается раскрывающийся список параметров.
В моей текущей реализации раскрывающийся список только отображается. после того, как пользователь дважды щелкнет ячейку таблицы. Затем пользователю необходимо снова щелкнуть раскрывающийся список, чтобы отобразить доступные параметры.
Вопрос:
Как всегда показывать QCombobox, и он будет открываться сразу же, когда пользователь щелкнет ячейку таблицы?
Пример кода
from enum import EnumMeta
from qgis.PyQt.QtWidgets import (
QStyledItemDelegate,
QWidget,
QComboBox,
)
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtCore import QModelIndex, QSize, QAbstractItemModel, Qt
from .shared_constants import CustomRoles
class BGCustomDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(BGCustomDelegate, self).__init__(parent)
self.setParent(parent)
def paint(self, painter: QPainter, option, index: QModelIndex) -> None:
QStyledItemDelegate.paint(self, painter, option, index)
def sizeHint(self, option, index: QModelIndex) -> QSize:
return QStyledItemDelegate.sizeHint(self, option, index)
def createEditor(self, parent: QWidget, option, index: QModelIndex) -> QWidget:
if index.data(CustomRoles.dataType.value) == EnumMeta:
editor = QComboBox(parent)
allowed_values_enum: EnumMeta = index.data(CustomRoles.allowedValues.value)
allowed_values = [e.value for e in allowed_values_enum]
editor.addItems(allowed_values)
return editor
else:
return QStyledItemDelegate.createEditor(self, parent, option, index)
def setEditorData(self, editor: QWidget, index: QModelIndex) -> None:
if index.data(CustomRoles.dataType.value) == EnumMeta:
editor: QComboBox
current_value = index.data(Qt.EditRole)
combo_index = editor.findText(current_value)
if combo_index >= 0:
editor.setCurrentIndex(combo_index)
else:
QStyledItemDelegate.setEditorData(self, editor, index)
def setModelData(
self, editor: QWidget, model: QAbstractItemModel, index: QModelIndex
) -> None:
if index.data(CustomRoles.dataType.value) == EnumMeta:
editor: QComboBox
current_value = editor.currentText()
model.setData(index, current_value, Qt.EditRole)
else:
QStyledItemDelegate.setModelData(self, editor, model, index)
Подробнее здесь: https://stackoverflow.com/questions/791 ... leview-not
В PyQT 5 всегда отображайте QCombobox, используя QStyledItemDelegate в QTableView (не только при редактировании ячейки) ⇐ Python
Программы на Python
1730948645
Anonymous
Я создаю подкласс QStyledItemDelegate, чтобы отображать раскрывающийся список QCombobox в QTableView. Делегат определяет тип данных из модели таблицы, и если dataType == EnumMeta, отображается раскрывающийся список параметров.
В моей текущей реализации раскрывающийся список только отображается. после того, как пользователь дважды щелкнет ячейку таблицы. Затем пользователю необходимо снова щелкнуть раскрывающийся список, чтобы отобразить доступные параметры.
[b]Вопрос:[/b]
Как всегда показывать QCombobox, и он будет открываться сразу же, когда пользователь щелкнет ячейку таблицы?
[b]Пример кода[/b]
from enum import EnumMeta
from qgis.PyQt.QtWidgets import (
QStyledItemDelegate,
QWidget,
QComboBox,
)
from qgis.PyQt.QtGui import QPainter
from qgis.PyQt.QtCore import QModelIndex, QSize, QAbstractItemModel, Qt
from .shared_constants import CustomRoles
class BGCustomDelegate(QStyledItemDelegate):
def __init__(self, parent=None):
super(BGCustomDelegate, self).__init__(parent)
self.setParent(parent)
def paint(self, painter: QPainter, option, index: QModelIndex) -> None:
QStyledItemDelegate.paint(self, painter, option, index)
def sizeHint(self, option, index: QModelIndex) -> QSize:
return QStyledItemDelegate.sizeHint(self, option, index)
def createEditor(self, parent: QWidget, option, index: QModelIndex) -> QWidget:
if index.data(CustomRoles.dataType.value) == EnumMeta:
editor = QComboBox(parent)
allowed_values_enum: EnumMeta = index.data(CustomRoles.allowedValues.value)
allowed_values = [e.value for e in allowed_values_enum]
editor.addItems(allowed_values)
return editor
else:
return QStyledItemDelegate.createEditor(self, parent, option, index)
def setEditorData(self, editor: QWidget, index: QModelIndex) -> None:
if index.data(CustomRoles.dataType.value) == EnumMeta:
editor: QComboBox
current_value = index.data(Qt.EditRole)
combo_index = editor.findText(current_value)
if combo_index >= 0:
editor.setCurrentIndex(combo_index)
else:
QStyledItemDelegate.setEditorData(self, editor, index)
def setModelData(
self, editor: QWidget, model: QAbstractItemModel, index: QModelIndex
) -> None:
if index.data(CustomRoles.dataType.value) == EnumMeta:
editor: QComboBox
current_value = editor.currentText()
model.setData(index, current_value, Qt.EditRole)
else:
QStyledItemDelegate.setModelData(self, editor, model, index)
Подробнее здесь: [url]https://stackoverflow.com/questions/79164899/in-pyqt-5-always-show-a-qcombobox-using-qstyleditemdelegate-in-qtableview-not[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия