Skip to content

Instantly share code, notes, and snippets.

@ialexpovad
Created December 1, 2022 07:57
Show Gist options
  • Save ialexpovad/59f2a498c0e131c897afbdeae92e1f3b to your computer and use it in GitHub Desktop.
Save ialexpovad/59f2a498c0e131c897afbdeae92e1f3b to your computer and use it in GitHub Desktop.
[Combo delegate] #pyqt5 #python
from PyQt5.QtCore import (Qt, pyqtSlot)
from PyQt5.QtWidgets import (QStyledItemDelegate, QComboBox)
class ComboDelegate(QStyledItemDelegate):
def __init__(self, parent, items):
self.items = items
QStyledItemDelegate.__init__(self, parent)
def createEditor(self, parent, option, index):
self.editor = QComboBox(parent)
font = self.editor.font()
font.setPointSize(8)
self.editor.setFont(font)
self.editor.setStyleSheet("background-color: white;\n"
"border: 1px solid gray;\n"
"padding: 1px 3px 1px 3px;")
self.editor.addItems(self.items)
self.editor.currentIndexChanged.connect(self.currentIndexChanged)
return self.editor
def setEditorData(self, editor, index):
editor.blockSignals(True) # block signals that are not caused by the user
value = index.data(Qt.DisplayRole)
if value == "":
editor.setStyleSheet("background-color: red")
else:
editor.setStyleSheet("background-color: white")
num = self.items.index(value)
editor.setCurrentIndex(num)
if index.column() == 1:
editor.showPopup()
editor.blockSignals(False)
def setModelData(self, editor, model, index):
model.setData(index, editor.currentText())
def updateEditorGeometry(self, editor, option, index):
editor.setGeometry(option.rect)
@pyqtSlot()
def currentIndexChanged(self):
self.commitData.emit(self.sender())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment