从QTableView中自定义代表组合框的选定项目

问题描述:

我使用自定义代理来在我的QTableView中显示组合框的列。 所有组合框的值都是相同的,所以它不是真正的人口部分给我带来麻烦。从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) 

,我把它叫做fromthe QTableView中是这样的:

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

希望我很清楚的,感谢您的关注

不确定从委托访问数据库是否正确。您的委托可以包含对QTableView引用的QAbstractTableModel实例的引用。然后,您可以使用模型中的方法遍历表的各行。

+0

那么我设法在compboBoxes中显示正确的选定项目。但正如你所说,我正在从代理访问数据库,但我真的不知道如何实现你的建议。我仍然有一个问题:当我重新排列tableView时,comboBoxes不会“跟随”.. – Johanna 2011-05-12 10:17:08

+0

是否可以从模型中调用委托的重绘? – Johanna 2011-05-12 12:15:01

+0

但模型如何知道委托,确定您可以将委托引用传递给模型。代表是他们改进表示(即更好的观点)使模型和委托相互依存会使你的代码变得脆弱。 – sateesh 2011-05-12 13:37:44