QCombobox 设置项目委托不为当前项目绘制..
我正在尝试创建一个组合框,显示不同的线类型(实线、虚线、虚线等)。目前我正在为其内容设置项目委托,以便绘制/绘制线型而不是显示名称。所有线型都在正确绘制,但是一旦我从组合框中选择任何线型,组合框的当前索引仅显示线名而不是绘制它。如何让它在当前组合框索引上绘制选定的线型?
QCombobox 设置项目委托不为当前项目绘制..
我正在尝试创建一个组合框,显示不同的线类型(实线、虚线、虚线等)。目前我正在为其内容设置项目委托,以便绘制/绘制线型而不是显示名称。所有线型都在正确绘制,但是一旦我从组合框中选择任何线型,组合框的当前索引仅显示线名而不是绘制它。如何让它在当前组合框索引上绘制选定的线型?
委托在组合弹出窗口中绘制项目:
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)
I think I've encountered this problem before, having a delegate that displays the line correctly in the drop-down menu but not in the combo box itself.
The documentation (http://doc.trolltech.com/4.4/qcombobox.html) states that:
"For the text and icon in the combobox label, the data in the model that has the Qt::DisplayRole and Qt::DecorationRole is used."
I suspect that an approach which involves a model that returns suitable data for the DecorationRole might work, but it could be problematic to get it to behave just the way you want it to.
您还可以将图像保存为图标并使用 QComboBox::setIconSize() 来避免缩放。
只需覆盖paintEvent。这是一些草图代码:
void PenComboBox::paintEvent( QPaintEvent* pEvent)
{
QComboBox::paintEvent( pEvent);
QVariant itemData = this->itemData( this->currentIndex(), Qt::DisplayRole);
if( !itemData.isNull() && qVariantCanConvert<QPen>( itemData))
{
QPainter painter(this);
// .. etc
}
}