In the previous section, we discussed how to apply style sheets to Qt Widgets through C++ coding. Although that method works really well, most of the time, the person who is in charge of designing the program's UI is not the programmer, but rather a UI designer who specializes in designing user-friendly UI. In this case, it's better to let the UI designer design the program's layout and style sheet with a different tool and not mess around with the code. Qt provides an all-in-one editor called Qt Creator.
Qt Creator consists of several different tools, such as script editor, compiler, debugger, profiler, and UI editor. The UI editor, which is also called Qt Designer, is the perfect tool for designers to design their program's UI without writing any code. This is because Qt Designer adopted the what you see is what you get approach by providing an accurate visual representation of the final result, which means whatever you design with Qt Designer will turn out exactly the same visually when the program is compiled and run.
The similarities between Qt Style Sheets and CSS are as follows:
- This is how a typical piece of CSS code looks:
h1 { color: red; background-color: white;}
- This is how Qt Style Sheets look, which is almost the same as the preceding CSS:
QLineEdit { color: red; background-color: white;}
As you can see, both of them contain a selector and a declaration block. Each declaration contains a property and a value, separated by a colon. In Qt, a style sheet can be applied to a single widget by calling the QObject::setStyleSheet() function in C++ code. Consider the following, for example:
myPushButton->setStyleSheet("color : blue");
The preceding code will turn the text of a button with the myPushButton variable name to blue. You can achieve the same result by writing the declaration in the style sheet property field in Qt Designer. We will discuss Qt Designer more in the following Customizing basic style sheets section.
Qt Style Sheets also supports all the different types of selectors defined in the CSS2 standard, including the universal selector, type selector, class selector, and ID selector, which allows us to apply styling to a very specific individual widget or group of widgets. For instance, if we want to change the background color of a specific line-edit widget with the usernameEdit object name, we can do this by using an ID selector to refer to it:
QLineEdit#usernameEdit { background-color: blue }