Gray Background for Read-Only QLineEdit

Setting a text box (aka QLineEdit) to read-only in QT doesn't make it's background gray as one would normally expect. Background remains as is with user confused as to why text cannot be changed. Classic Windows solution of graying out background seems much better to me and I decided to replicate the same.

My requirements for this were just two. It had to work correctly under both Windows and Linux. And it couldn't use static color but follow the overall theme.

The first idea was to use background role.

ui->lineEdit->autoFillBackground(true);
ui->lineEdit->setBackgroundRole(QPalette::Window);

And, even with background auto-filling set, this doesn't work.

As I was after the same color as window background, setting the whole text box transparent seemed at least plausible.

ui->lineEdit->setStyleSheet("background: transparent;");

This sort-of worked but with only top border-line visible instead of full rectangle. Passable but ugly.

After a few more false starts, I finally found code that fulfills both requirements.

QPalette readOnlyPalette = ui->lineEdit->palette();
readOnlyPalette.setColor(QPalette::Base, ui->lineEdit->palette().color(QPalette::Window));
ui->lineEdit->setPalette(readOnlyPalette);

Essentially, we modify palete and set it's color to what Window would use. A bit more involved than just setting read-only property but I guess not too difficult either.

2 thoughts to “Gray Background for Read-Only QLineEdit”

  1. FYI there is an easier way…

    setStyleSheet(“QLineEdit:read-only{background: palette(window);}”);

Leave a Reply

Your email address will not be published. Required fields are marked *