Can't use painter->fillRect with custom color



  • Hey,
    I want to paint a rectangle in the drawBackground function of a QGraphicsView.
    But I want to use a custom color.
    So I tried:

        QColor *myColor = new QColor(71, 71, 71, 255);
        painter->fillRect(rect.intersected(sceneRect), myColor);
    

    Then I get this error in the second line:

    error: invalid conversion from 'const QColor*' to 'QRgb {aka unsigned int}' [-fpermissive]
    

    i really don't understand that, when I try:

        QColor myColor = new QColor(71, 71, 71, 255); // no pointer!
        painter->fillRect(rect.intersected(sceneRect), myColor);
    

    I get this error in the first line:

    error: invalid conversion from 'QColor*' to 'QRgb {aka unsigned int}' [-fpermissive]
         QColor myColor = new QColor(71, 71, 71, 255);
    

    I have no Idea what this means, I even do not use any QRgb here so I don't know what is wrong with this code
    What should I write instead and what does the error mean?
    Thanks for answers



  • Found it!
    just had to use

        painter->fillRect(rect.intersected(sceneRect), myColor->rgb());
    

    But I still don't know why it says

    invalid conversion
    

    in the first line, when I do not use myColor->rgb()
    There was nothing wrong with the first line...



  • QPainter::fillRect expects QBrush or QColor and you are trying to call it with QColor pointer.

    QColor *myColor = new QColor(71, 71, 71, 255);
    painter->fillRect(rect.intersected(sceneRect), myColor);
    
    QColor myColor = new QColor(71, 71, 71, 255);
    

    These both try to create QColor using QColor* value and QColor(QRgb) seems to be closest constructor for this conversion.

    painter->fillRect(rect.intersected(sceneRect), myColor->rgb());
    

    And you create QColor using QRgb.


  • Lifetime Qt Champion

    Hi,

    You are creating a memory leak here. There's not need to create your QColour object on the heap. Just use the stack.

    const QColor myColor(71, 71, 71, 255);
    painter->fillRect(rect.intersected(sceneRect), myColor);
    

    Or even shorter:

    painter->fillRect(rect.intersected(sceneRect), QColor(71, 71, 71, 255));
    


  • @SGaist
    Ok, thanks!
    Will I also be able to keep this method when I add the possibility in the program to change this color at runtime?


  • Lifetime Qt Champion

    Yes, just make your myColor variable a class member and update it as you want it.


Log in to reply
 

Looks like your connection to Qt Forum was lost, please wait while we try to reconnect.