How to set color



  • I have a list of cars, which have different colors. When the user enters a color I want all cars with the same color to be highlighted with that.
    I have tried something like this, but it doesn't work.
    string color = colorEdt->text().toStdString();
    ....
    item->setData(Qt::BackgroundRole,QColor::setNamedColor(color));
    Could you give me some tips?

    item->setData(Qt::BackgroundRole,QColor::setNamedColor(color));


  • Qt Champions 2016

    @shanto
    Hello,
    We would need some more code. What kind of list is that, is it a QListWidget? Where do you call item->setData(Qt::BackgroundRole,QColor::setNamedColor(color)), is it connected to a signal?
    And finally a note:

    string color = colorEdt->text().toStdString();
    

    Don't convert to std::string without any good reason, use Qt's QString instead, it's also is implicitly shared (which std::string is not) so there won't be unnecessary copying involved.

    Kind regards.



  • @kshegunov Hi! So here's what I'm trying to do:

    void UI::colorCars()
    {
        //I get the color from a QLineEdit
        string color = colorEdt->text().toStdString(); 
    
        //list contains the current cars in repository and guiList is a QListWidget
        std::vector<Car> llist = carCon.getCarsController();
        guiList->clear();
    
        for(Car& car : list)
        {
            QListWidgetItem* item = new QListWidgetItem(QString::fromStdString(car.getNrMatr()),guiList);
            item->setData(Qt::UserRole,QVariant::fromValue(car.getId()));
            
            //I compare each car in the list with "color" and if it is the same I have to color the item with it(blue,green,yellow etc.)
            if(car.getColor() == color)
            {
                item->setData(Qt::BackgroundRole,QColor(Qt::color));
            }
        }
    }
    

  • Qt Champions 2016

    @shanto
    Hello,

    item->setData(Qt::BackgroundRole, QColor(Qt::color));
    

    This doesn't look correct. I'd try something like this:

    item->setData(Qt::BackgroundRole, QColor(QString::fromStdString(color)));
    

    But the color name should be parse-able, otherwise you'd an invalid color.



  • @kshegunov Thanks a lot! It works now. :)


Log in to reply
 

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