Home > front end >  QT: Use stylesheet as external file
QT: Use stylesheet as external file

Time:10-13

I have a project developed in QT 5.9.5, so C . I have an with a GUI and I want to describe the appereance of the widgets with an external global stylesheet. I'm working with QTCreator. I added a general file named "stylesheet.qss" and QTCreator put it into "Other files" directory. I have not created resources files. Only the qss file inside the "Other files" directory. To call the file, I write in the mainwindow.cpp (mainwindow is the user interface, mainwindow.ui) the following code:

QFile file(":/stylesheet.qss");
file.open(QIODevice::ReadWrite);
QTextStream in(&file);
QString text;
text = in.readAll();
file.close();
setStylesheet(text);

When I run the app, the application output give me the following problem:

QIODevice::read (QFile, ":/stylesheets.qss"): device not open

Instead, if I write:

QFile file("stylesheet.qss");

And also if I write:

file.open(QIODevice::ReadOnly);

the problem doesn't occur. However, in all the cases, the variable text is empty and I can't use stylesheet. Checking the file.errorString(), it gives:

"Unknown error"

and checking the file.error(), it gives:

0

Someone can suggest me a solution or another way to add a stylesheet to my app? Thank you, Marco

CodePudding user response:

  1. add your .qss File in Resource(.qrc)

  2. put this code that you want to add your qss in your program in main.cpp :

#include "mainwindow.h"

#include <QApplication>
#include <QFile>

int  main(int argc, char *argv[])
{
    QApplication  a(argc, argv);

    /**
     * Load the application style
     */
    QFile  styleFile(":/Style.qss");

    styleFile.open(QFile::ReadOnly);

    /**
     * Apply the loaded stylesheet
     */
    QString  style(styleFile.readAll());
    a.setStyleSheet(style);

    MainWindow  w;
    w.show();

    return a.exec();
}
  • Related