【问题标题】:How do create delegate to display icon and text of QComboBox in QTreeWidget (PyQt)?如何创建委托以在 QTreeWidget (PyQt) 中显示 QComboBox 的图标和文本?
【发布时间】:2014-06-03 05:11:59
【问题描述】:

我在尝试在 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_())

【问题讨论】:

    标签: qt delegates pyqt qcombobox


    【解决方案1】:

    对于任何标准视图,获取图标不是委托的工作。将图标放入视图的标准方法是在视图调用data(index, Qt::DecorationRole)时返回QIcon

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

    【讨论】:

    • 谢谢你,我也在尝试使用paint方法,所以我很高兴发现它更容易——但它是“DecorationRole”(QtCore.Qt.DecorationRole)。我冒昧地编辑了您的答案。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-10-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-01-18
    • 2018-03-19
    相关资源
    最近更新 更多