Flying Jay
Flying Jay

Reputation: 359

How to set global style sheets to custom widgets?

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

Upvotes: 1

Views: 2695

Answers (2)

Toby Speight
Toby Speight

Reputation: 30834

Yes, styles will work just fine on your own widgets.

If you have non-standard properties you want to set, you'll need to declare them using Q_PROPERTY. For example:

class MyWidget : public QWidget
{
     Q_OBJECT
     Q_PROPERTY(QString extra READ extra WRITE setExtra)
     //...
};

You can then style it:

MyWidget {
 background-color: blue;
 color: yellow;
 qproperty-extra: "Some extra text";
}

For the widget in your code sample, the background is never drawn. Its constructor needs to be changed to ask Qt to draw the background using the style information:

MyCustomWidget(QWidget *parent) : QWidget(parent) {
    setAttribute(Qt::WA_StyledBackground);
}

Upvotes: 1

dydil
dydil

Reputation: 1007

When applying stylesheets to a custom QWidget-derived class, do not forget to override the paintEvent as mentionned in the documentation:

QWidget Supports only the background, background-clip and background-origin properties.

If you subclass from QWidget, you need to provide a paintEvent for your custom QWidget as below

Warning: Make sure you define the Q_OBJECT macro for your custom widget.

void CustomWidget::paintEvent(QPaintEvent *)
{
    QStyleOption opt;
    opt.init(this);
    QPainter p(this);
    style()->drawPrimitive(QStyle::PE_Widget, &opt, &p, this);
}

Upvotes: 0

Related Questions