выбранный элемент comboBox в пользовательском делегате из QTableView - PullRequest
2 голосов
/ 10 мая 2011

Я использую пользовательский делегат для отображения столбца comboBox в моем QTableView. Значения одинаковы для всех комбинированных списков, поэтому проблема не в населении.

Я хочу, чтобы они отображали в качестве выбранного элемента какое-то значение, которое я могу извлечь из базы данных. У меня есть доступ к базе данных от делегата, но для отправки моего запроса мне нужен ряд comboBox.

Итак, я предполагаю, что мой вопрос: как вы можете перебрать все строки таблицы и выполнить какое-то действие внутри пользовательского делегата?

Если это может помочь, вот мой класс делегата:

class ComboBoxDelegate(QtGui.QItemDelegate):

def __init__(self, parent, itemslist):
    QtGui.QItemDelegate.__init__(self, parent)
    self.itemslist = itemslist
    self.parent = parent

def paint(self, painter, option, index):        
    # Get Item Data
    value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
    # value = self.itemslist[index.data(QtCore.Qt.DisplayRole).toInt()[0]]
    # fill style options with item data
    style = QtGui.QApplication.style()
    opt = QtGui.QStyleOptionComboBox()
    opt.currentText = str(self.itemslist[value])
    opt.rect = option.rect


    # draw item data as ComboBox
    style.drawComplexControl(QtGui.QStyle.CC_ComboBox, opt, painter)
    self.parent.openPersistentEditor(index)

def createEditor(self, parent, option, index):

    ##get the "check" value of the row
    # for row in range(self.parent.model.rowCount(self.parent)):
        # print row

    self.editor = QtGui.QComboBox(parent)
    self.editor.addItems(self.itemslist)
    self.editor.setCurrentIndex(0)
    self.editor.installEventFilter(self)    
    self.connect(self.editor, QtCore.SIGNAL("currentIndexChanged(int)"), self.editorChanged)

    return self.editor

# def setEditorData(self, editor, index):
    # value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
    # editor.setCurrentIndex(value)

def setEditorData(self, editor, index):
    text = self.itemslist[index.data(QtCore.Qt.DisplayRole).toInt()[0]]
    pos = self.editor.findText(text)
    if pos == -1:  
        pos = 0
    self.editor.setCurrentIndex(pos)


def setModelData(self,editor,model,index):
    value = self.editor.currentIndex()
    model.setData(index, QtCore.QVariant(value))


def updateEditorGeometry(self, editor, option, index):
    self.editor.setGeometry(option.rect)

def editorChanged(self, index):
    check = self.editor.itemText(index)
    id_seq = self.parent.selectedIndexes[0][0]
    update.updateCheckSeq(self.parent.db, id_seq, check)

И я называю это из QTableView так:

self.setEditTriggers(QtGui.QAbstractItemView.CurrentChanged)
self.viewport().installEventFilter(self)
self.setItemDelegateForColumn(13,ComboBoxDelegate(self, self.checkValues))

Надеюсь, я был достаточно ясен, спасибо за ваше внимание

1 Ответ

1 голос
/ 11 мая 2011

Не уверен, что доступ к базе данных от делегата является правильным решением.Ваш делегат может содержать ссылку на экземпляр QAbstractTableModel, на который ссылается QTableView.Затем вы можете использовать методы в модели для перебора строк таблицы.

...