Style Sheet UsageCustomizing the Foreground and Background Colors
Let's start by setting yellow as the background color of all QLineEdits in an application. This could be achieved like this:
- qApp->setStyleSheet("QLineEdit { background-color: yellow }");
If we want the property to apply only to the QLineEdits that are children (or grandchildren or grand-grandchildren) of a specific dialog, we would rather do this:
- myDialog->setStyleSheet("QLineEdit { background-color: yellow }");
If we want the property to apply only to one specific QLineEdit, we can give it a name using QObject::setObjectName() and use an ID Selector to refer to it:
- myDialog->setStyleSheet("QLineEdit#nameEdit { background-color: yellow }");
Alternatively, we can set the background-color property directly on the QLineEdit, omitting the selector:
- nameEdit->setStyleSheet("background-color: yellow");
To ensure a good contrast, we should also specify a suitable color for the text:
- nameEdit->setStyleSheet("color: blue; background-color: yellow");
It might be a good idea to change the colors used for selected text as well:
- nameEdit->setStyleSheet("color: blue;"
- "background-color: yellow;"
- "selection-color: yellow;"
- "selection-background-color: blue;");