Qt Set Background Color of QLineEdit

36,767

Solution 1

Works fine for me:

QLineEdit *le = new QLineEdit();
le->setStyleSheet("QLineEdit { background: rgb(0, 255, 255); selection-background-color: rgb(233, 99, 0); }");

Solution 2

You can set the background and text colors of line edit by setting the palette like :

QLineEdit *le = new QLineEdit();

QPalette palette;
palette.setColor(QPalette::Base,Qt::black);
palette.setColor(QPalette::Text,Qt::white);
le->setPalette(palette);

Solution 3

Your code is almost correct. Only QLine edit uses the Base color. So if you do not want to replace existing stylesheet which can contain borders padding and margin and you want to change background only, use QPalette:

QPalette palette = _ui->lnSearch->palette();
palette.setColor(QPalette::Base, Qt::green);
_ui->lnSearch->setPalette(palette);

Thanks to: https://forum.qt.io/topic/64568/why-setting-background-color-of-qlineedit-has-no-effect

Solution 4

I had to use background-color from standard css like this:

QLineEdit* edit = new QLineEdit();
edit->setStyleSheet("QLineEdit {background-color: black;}");

I am using Qt 5.4

Share:
36,767
David Ludwig
Author by

David Ludwig

I'm an expert web designer and Python programmer. I can program in all of the big languages including C, C++ and Java as well as a variety of scripting languages.

Updated on July 18, 2022

Comments

  • David Ludwig
    David Ludwig almost 2 years

    I'm trying to change the background color of the QLineEdit and I can't figure it out at all.

    I tried using stylesheets originally like this

    QLineEdit *le = new QLineEdit();
    le->setStyleSheet("background:#000;");
    

    but that didn't do anything. I tried using QPalette like this

    QPalette palette;
    palette.setColor(QPalette::Base, Qt::black);
    palette.setColor(QPalette::Background, Qt::black);
    le.setPalette(palette);    
    

    but this didn't do anything either. I've been looking all day and can't find anything. am I doing something wrong or is there another way to do it?

  • David Ludwig
    David Ludwig over 9 years
    Ah I found what it was it was just because the window had the Qt::WA_TranslucentBackground attribute. That has been driving me crazy all day. thanks though
  • Iuliu
    Iuliu over 9 years
    @DavidLudwig I'm glad you figured it out. Marking the answer as accepted would be helpful considering it's a valid answer anyway...