如何在QTreeWidget(PyQt)中创建委托来显示QComboBox的图标和文本?

时间:2014-04-18 16:45:39

标签: qt delegates pyqt qcombobox

我在尝试在QTreeWidget中显示图标和文字时遇到了一些麻烦。我的QTreeWidget只显示文字!!如何使用paint方法显示图标和文字?非常感谢!代码如下:

from PyQt4 import QtGui,QtCore
import sys
class ColorComboBox(QtGui.QComboBox):   
    def __init__(self,parent=None):
        super(ColorComboBox,self).__init__(parent)
        colorList=['yellow','red']       
        for color in colorList:
            pix=QtGui.QPixmap(QtCore.QSize(20,20))
            pix.fill(QtGui.QColor(color))
            self.addItem(QtGui.QIcon(pix),color)           
class CustomsDelegate(QtGui.QStyledItemDelegate):
    def __init__(self,parent=None):
        super(CustomsDelegate,self).__init__(parent)       
    def paint(self,painter,option,index):
        painter.save()                  
        painter.setPen(QtGui.QPen(QtCore.Qt.white))
        value = index.data(QtCore.Qt.DisplayRole)
        if value.isValid():
            text = value.toString() 
            painter.drawText(option.rect, QtCore.Qt.AlignLeft, text)    
        painter.restore()
    def createEditor(self, parent, option, index):
        self.combo = ColorComboBox(parent)
        return self.combo    
    def setEditorData(self, editor, index):
        value = index.model().data(index, QtCore.Qt.EditRole).toString()
        editor.setCurrentIndex(editor.findText(value))        

    def setModelData(self, editor, model, index):
        if editor.currentIndex() >= 0:
            realidx = editor.model().index(editor.currentIndex(), 0) 
            value = editor.model().data(realidx)        
            model.setData(index, value, QtCore.Qt.EditRole)                              
class B(QtGui.QTreeWidget):
    def __init__(self,parent=None):
        super(B,self).__init__(parent)            
        self.setColumnCount(2)      
        x = QtGui.QTreeWidgetItem()
        x.setText(0,'text1')   
        y = QtGui.QTreeWidgetItem()     
        x.setFlags(x.flags()|QtCore.Qt.ItemIsEditable)
        self.addTopLevelItems([x,y])
        self.setItemDelegateForColumn(1,CustomsDelegate(self))     
if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    b = B()
    b.show()
    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:1)

对于任何标准视图,获取一个图标而不是代理的工作。将图标添加到视图的标准方法是在视图调用QIcon时返回data(index, Qt::DecorationRole)

将您的图标代码放入模型中,视图将自行处理。