In the main window I can set CSS styles for different standard widgets:
setStyleSheet("QComboBox { background-color: red; } QLabel { background-color: blue; }")
These styles will be applied in child widgets with those names.
But is it possible to set styles for widgets defined by me in the same fashion?
Then this widget should obtain its style by its class name. I can't seem to find corresponding function that would obtain the style sheet by class name.
Here is an example.
---custom-widget.h---
#include <QWidget>
class MyCustomWidget : public QWidget {
Q_OBJECT
public:
MyCustomWidget(QWidget *parent) : QWidget(parent) { }
};
---main.cpp---
#include <QApplication>
#include <QWidget>
#include <QLayout>
#include <QLabel>
#include "custom-widget.h"
int main(int argc, char **argv) {
QApplication app (argc, argv);
QWidget mainWindow;
QVBoxLayout mainLayout(&mainWindow);
QLabel label("I am a label", &mainWindow);
MyCustomWidget customWidget(&mainWindow);
mainLayout.addWidget(&label);
mainLayout.addWidget(&customWidget);
customWidget.setMinimumSize(100, 300);
mainWindow.setStyleSheet(
"QLabel { background-color: #5ea6e3; }"
"MyCustomWidget { background-color: #f00000; }"
);
mainWindow.show();
return app.exec();
}
---main.pro---
CONFIG += qt
QT += core gui widgets
TEMPLATE = app
TARGET = main
HEADERS = main.h custom-widget.h
SOURCES = main.cpp
setStyleSheet
- Vahagn AvagyanmainWindow.setStyleSheet( "QLabel { background-color: #5ea6e3; }" "MyCustomWidget { background-color: #f00000; }" );
After that you will lose steyle on MyCustomWidget - Vahagn AvagyanQWidget
with no contents. Unless you actually use the background colour, you won't see any visual effect. - Toby Speight