1

I'm trying to use a Q_PROPERTY set in my stylesheet to change the value in QPalette, is this possible? For example, if I set QStyle to Fusion in my MainWindow widget, is it possible to change Qt::Window, etc using this method?

Everything compiles OK, but the only color displayed is black, so the variable is probably filled with a garbage value? As far as I know, the stylesheet overrides everything else, so at a guess, the stylesheet is not loaded in time for the constructor?

mainwindow.cpp

#include <QStyleFactory>
#include <QWidget>
#include <QFile>
#include "theme.h"

MainWindow::MainWindow(QWidget *parent) :
    QMainWindow(parent),
{
    QFile File("://stylesheet.qss");
    File.open(QFile::ReadOnly);
    QString StyleSheet = QLatin1String(File.readAll());
    qApp->setStyleSheet(StyleSheet);

    Theme *themeInstance = new Theme;

    QApplication::setStyle(QStyleFactory::create("Fusion"));

    QPalette dp;
    dp.setColor(QPalette::Window, QColor(themeInstance->customColor()));
    qApp->setPalette(dp);
}

theme.h

#ifndef THEME_H
#define THEME_H

class Theme : public QWidget
{
    Q_OBJECT
    Q_PROPERTY(QColor customColor READ customColor WRITE setCustomColor DESIGNABLE true)
public:
    Theme(QWidget *parent = nullptr);

    QColor customColor() const { return m_customColor; }
    void setCustomColor(const QColor &c) { m_customColor = c; }
private:
    QColor m_customColor;
};

#endif // THEME_H

stylesheet.qss

* { // global only for test purposes
    qproperty-customColor: red;
}
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
RyuMake
  • 25
  • 3

1 Answers1

0

The QSS are not called automatically, they are usually updated when the widgets are displayed, in your case as themeInstance is not shown does not use the stylesheet. Painting can be forced using the polish() method of QStyle

class MainWindow : public QMainWindow
{
    Q_OBJECT
public:
    explicit MainWindow(QWidget *parent = nullptr):QMainWindow{parent}{
        qApp->setStyleSheet("Theme{qproperty-customColor: red;}");
        Theme *themeInstance = new Theme;
        qApp->setStyle(QStyleFactory::create("Fusion"));
        qApp->style()->polish(themeInstance);
        QPalette dp;
        dp.setColor(QPalette::Window, QColor(themeInstance->customColor()));
        qApp->setPalette(dp);
    }
};
eyllanesc
  • 235,170
  • 19
  • 170
  • 241
  • @RyuMake I have a curiosity, why are you doing that? – eyllanesc Apr 23 '18 at 23:03
  • I have multiple themes in separate qss files that can be changed from a settings panel in the program. I had to use qss since a lot of widgets are custom made. I wanted to try and utilize QStyle since it handles base widgets fairly well, so i could remove those from the qss files and shrink them a bit. – RyuMake Apr 24 '18 at 01:13