Qt World Summit: Register Today!

I get the wrong color in paint function.

  • //ShowImgScene
    void ShowImgScene::AddRect(QRect &rect, QColor color /*= QColor(Qt::red)*/)
        QPen pen;
        QGraphicsRectItem * pRectItem = new GraphicsRectItem(rect); // GraphicsRectItem
        pRectItem->setPen(pen); // at here i set the pen

    I wan to get the color in GraphicsRectItem::paint function.

    void GraphicsRectItem::paint(QPainter *painter, const QStyleOptionGraphicsItem *option, QWidget *widget)
        QColor color = painter->pen().color(); // but the color always is black
        if( option->state & QStyle::State_Selected ){

    where is i wrong? and, how to get the color of before set in paint function?

    About this problem, i can use the setData and data. But, i think there must be a better way.

  • @joeQ I think you should use "this->pen()" to access the colour of the graphics item. You're accessing the last pen set on the painter instead.

    Please try this…

    QColor color = pen().color();

    (I'm working from memory, apologise if I'm wrong!)

  • @matthew.kuiash

    Excellent, Your memory is good! Thank u very much.

Log in to reply