QCombobox设置Item delegate不绘制当前Item ..
我正在尝试创建一个显示不同线型的组合框(Solid,Dotted,Dash等).目前我正在为其内容设置项目委托
以绘制/绘制线型而不是显示名称.所有线型现在都在绘制,但只要我从中选择任何线型
组合框,组合框的当前索引只显示行名而不是绘制它.如何使其在当前绘制选定的线型
组合框索引?
最佳答案 委托在组合弹出窗口中绘制项目:
class LineStyleDelegate(QtGui.QItemDelegate):
def __init__(self, object, parent = None):
QtGui.QItemDelegate.__init__(self, parent)
def paint(self, painter, option, index):
data = index.model().data(index, QtCore.Qt.UserRole)
if data.isValid() and data.toPyObject() is not None:
data = data.toPyObject()
painter.save()
rect = option.rect
rect.adjust(+5, 0, -5, 0)
pen = QtGui.QPen()
pen.setColor(QtCore.Qt.black)
pen.setWidth(3)
pen.setStyle(data)
painter.setPen(pen)
middle = (rect.bottom() + rect.top()) / 2
painter.drawLine(rect.left(), middle, rect.right(), middle)
painter.restore()
else:
QtGui.QItemDelegate.paint(self, painter, option, index)
painter.drawLine(rect.left(), middle, rect.right(), middle)
painter.restore()
else:
QtGui.QItemDelegate.paint(self, painter, option, index)
paintEvent在组合中绘制当前项.当然,您可以手动绘制它,但有一种简单的方法来绘制组合框控件本身(如果您想要当前的箭头按钮或smth):
def paintEvent(self, e):
data = self.itemData(self.currentIndex(), QtCore.Qt.UserRole)
if data.isValid() and data.toPyObject() is not None:
data = data.toPyObject()
p = QtGui.QStylePainter(self)
p.setPen(self.palette().color(QtGui.QPalette.Text))
opt = QtGui.QStyleOptionComboBox()
self.initStyleOption(opt)
p.drawComplexControl(QtGui.QStyle.CC_ComboBox, opt)
painter = QtGui.QPainter(self)
painter.save()
rect = p.style().subElementRect(QtGui.QStyle.SE_ComboBoxFocusRect, opt, self)
rect.adjust(+5, 0, -5, 0)
pen = QtGui.QPen()
pen.setColor(QtCore.Qt.black)
pen.setWidth(3)
pen.setStyle(data)
painter.setPen(pen)
middle = (rect.bottom() + rect.top()) / 2
painter.drawLine(rect.left(), middle, rect.right(), middle)
painter.restore()
else:
QtGui.QComboBox.paintEvent(self, e)