Jai
Jai

Reputation: 1332

How to inherite stylesheet from QApplication in Qt/C++

I am using external and universal stylesheet through reading qss file like below

QFile File("../Stylesheet.qss");
File.open(QFile::ReadOnly);
QString StyleSheet = QLatin1String(File.readAll());
pApp->setStyleSheet(StyleSheet);

stylesheet.qss is good and working

Problem
I have a widget which initialize with no parent. like

WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow)
    : QWidget()
{}

because of this stylesheet is not applying on WorkspaceWindow & its children widget.

My Approach
I created a dummy class which inherits from QWidget and set stylesheet on this class at constructor.

class PrimaryWidget:public QWidget;

PrimaryWidget::PrimaryWidget()
{
    QFile File("../Stylesheet.qss");
    File.open(QFile::ReadOnly);
    QString StyleSheet = QLatin1String(File.readAll());
    setStyleSheet(StyleSheet);
}

static PrimaryWidget& get()
{
     static PrimaryWidget obj;
     return obj;
}

now I am using WorkspaceWindow as

WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow)
    : QWidget(&PrimaryWidget::get())
{}

now It working fine.

Question
How can avoid this scenario ? can I use QApplication object to initialize stylesheet for orphan objects (like WorkspaceWindow) ? or make WorkspaceWindow child of QApplication (kind of) ?

Upvotes: 0

Views: 456

Answers (1)

JefGli
JefGli

Reputation: 791

Using a dummy widget as parent for the soul purpose of setting a style sheet just doesn't feel right.

I would change your code to:

namespace myApp
{
    QString styleSheet()
    {
        QFile file("../Stylesheet.qss");
        file.open(QFile::ReadOnly);
        const QString styleSheet = QLatin1String(File.readAll());
        return styleSheet;
    }
}

And in the constructor of your widget simply:

WorkspaceWindow::WorkspaceWindow(WorkspaceWindow* pWorkspaceWindow, QWidget *parent)
: QWidget(parent)
{
    if (parent == Q_NULLPTR) {
        setStyleSheet(myApp::styleSheet());
    }
}

Upvotes: 2

Related Questions