如何让QCombobox绘画项目代表它的当前项目? (Qt 4)

时间:2009-02-05 14:08:45

标签: qt qt4 qcombobox qitemdelegate

QCombobox设置项目委托不为当前项目绘画..

我正在尝试创建一个显示不同线型的组合框(Solid,Dotted,Dash等)。目前我正在为其内容设置项目委托 以绘制/绘制线型而不是显示名称。所有线型现在都在绘制,但只要我从中选择任何线型 组合框,组合框的当前索引只显示行名而不是​​绘制它。如何使其在当前绘制选定的线型 组合框索引?

4 个答案:

答案 0 :(得分:3)

委托在组合弹出窗口中绘制项目:

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)

答案 1 :(得分:0)

我想我以前遇到过这个问题,让代理人在下拉菜单中正确显示该行,但不在组合框本身中。

文档(http://doc.trolltech.com/4.4/qcombobox.html)声明:

“对于组合框标签中的文本和图标,使用模型中具有Qt :: DisplayRole和Qt :: DecorationRole的数据。”

我怀疑涉及一个为DecorationRole返回合适数据的模型的方法可能有效,但让它按照您希望的方式运行可能会有问题。

答案 2 :(得分:0)

您还可以将图像保存为图标,并使用QComboBox :: setIconSize()来避免缩放。

答案 3 :(得分:-1)

只需覆盖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
  }
}