Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import sys
- from PySide6.QtCore import QAbstractTableModel, QSize, Qt
- from PySide6.QtWidgets import QAbstractItemView, QApplication, QComboBox, QItemDelegate, QMainWindow, QStyle, QTableView
- class ComboBoxDelegate(QItemDelegate):
- def __init__(self, parent):
- super().__init__(parent)
- self.items = ['AAA', 'BBB', 'CCC']
- def createEditor(self, parent, option, index):
- editor = QComboBox(parent)
- editor.addItems(self.items)
- return editor
- def setEditorData(self, editor, index) -> None:
- editor.setCurrentText(index.model().data(index, Qt.ItemDataRole.EditRole))
- def setModelData(self, editor, model, index):
- model.setData(index, editor.currentText(), Qt.ItemDataRole.EditRole)
- def updateEditorGeometry(self, editor, option, index):
- editor.setGeometry(option.rect)
- def paint(self, painter, option, index):
- text = self.items[index.row()]
- option.text = text
- QApplication.style().drawControl(QStyle.CE_ItemViewItem, option, painter)
- class TableModel(QAbstractTableModel):
- def __init__(self):
- super().__init__()
- self.__data = [['AAA', 1], ['BBB', 2]]
- def rowCount(self, index):
- return len(self.__data)
- def columnCount(self, index):
- return len(self.__data[0])
- def headerData(self, section, orientation, role):
- if orientation == Qt.Horizontal and role == Qt.DisplayRole:
- if section == 0:
- return 'str'
- else:
- return 'int'
- def flags(self, index):
- return Qt.ItemFlag.ItemIsEnabled | Qt.ItemFlag.ItemIsSelectable | Qt.ItemFlag.ItemIsEditable
- def data(self, index, role):
- if index.isValid():
- match role:
- case Qt.ItemDataRole.EditRole:
- return self.__data[index.row()][index.column()]
- case Qt.ItemDataRole.DisplayRole:
- return self.__data[index.row()][index.column()]
- def setData(self, index, value, role = Qt.EditRole) -> bool:
- if index.isValid():
- match role:
- case Qt.ItemDataRole.EditRole:
- self.__data[index.row()][index.column()] = value
- self.dataChanged.emit(index, index)
- return True
- return False
- app = QApplication(sys.argv)
- window = QMainWindow()
- window.setFixedSize(QSize(800, 600))
- w = QTableView(window)
- w.setFixedSize(QSize(700, 550))
- w.verticalHeader().hide()
- w.setSelectionBehavior(QAbstractItemView.SelectRows)
- m = TableModel()
- w.setModel(m)
- w.selectRow(0)
- d = ComboBoxDelegate(w)
- w.setItemDelegateForColumn(0, d)
- window.setCentralWidget(w)
- window.show()
- app.exec()
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement