Nicolas Charvoz
Nicolas Charvoz

Reputation: 1509

Load an external stylesheet in Qt

I'm new to Qt, I read all the documentation about Stylesheets and I almost know how to style my app. My files are like this :

Project/ -> babel.pro resources.qrc gui/ -> QtFiles, stylesheet.qss app/ -> main.cpp

My main looks like this :

int main(int ac, char **av) {
  MyApplication app(ac, av);
  MyWidget widget;

  QFile File(":/gui/stylesheet.qss");                                                  
  File.open(QFile::ReadOnly);
  QString StyleSheet = QLatin1String(File.readAll());

  app.setStyleSheet(StyleSheet);
  widget.show();

  return app.exec();

}

MyApplication.hpp :

class MyApplication : public QApplication {

public:

  MyApplication(int argc, char **av) : QApplication(argc, av) {}
  virtual ~MyApplication() {}
  virtual bool notify(QObject *rec, QEvent *ev) {
    try {
      return QApplication::notify(rec, ev);
    }
    catch (const std::exception &e) {
      std::cerr << e.what() << std::endl;
      exit(0);
    }
    return false;
  }
};

And finally MyWidget.cpp :

MyWidget::MyWidget(QWidget *parent) : QWidget(parent)
{
  QVBoxLayout *mainLayout = new QVBoxLayout;

  setFixedSize(1920, 1200);
  setWindowTitle(tr("Babel"));

  _tabWidget = new QTabWidget;
  _tabWidget->addTab(new Home(), tr("Home"));
  _tabWidget->addTab(new Contact(), tr("Contact"));

  _tabWidget->resize(10, _tabWidget->height());

  mainLayout->addWidget(_tabWidget);
  setLayout(mainLayout);
}

I added this line in my babel.pro (which is the general .pro for the compilation) : RESOURCES += resources.qrc

But I have this error when running the app : QIODevice::read: device not open

EDIT :

My resources file looks like this :

<!DOCTYPE RCC>                                                                        
<RCC version="1.0">
     <qresource>
        <file>/gui/stylesheet.qss</file>
     </qresource>
</RCC>

Upvotes: 1

Views: 3218

Answers (1)

Nicolas Charvoz
Nicolas Charvoz

Reputation: 1509

The path was missing the ".", so /gui/stylesheet.qss became ./gui/stylesheet.qss ! And it worked as expected ..

Thank you for your time guys, a dumb mistake that I'm not going to repeat !

Upvotes: 1

Related Questions