Qt’s style system FTW (Adding Theme Support to a Qt Application)

A few years ago, I was asked to add “theme” to a Qt project of mine. I wasn’t fully aware of the power of Qt’s style system, so I did it the hard way. I created a configuration file which contained the theme-able attributes of just about everything I could think of. And when the application started, I parsed it, and applied the colors, fonts, etc. After a short bit, I noticed things I had overlooked and added them. It wasn’t amazingly hard, but it sure could have been easier. Today I’d like to discuss the easy way :-).

Using the following code, we can let the user customize just about any part of the look and feel of our Qt applications.

#include <QApplication>
#include <QFile>
#include "MainWindow.h"

int main(int argc, char *argv[]) {
	QApplication app(argc, argv);
	QFile file("myapp.style");

	if(file.open(QIODevice::ReadOnly)) {
		qApp->setStyleSheet(file.readAll());
	}

	MainWindow w;
	w.show();
	return app.exec();
}

That’s it! So how does this work?

After creating the core QApplication object, we attempt to open a file. The name can of course be anything of our choosing. But “myapp.style” works just fine for now. If we succeeded, we read the whole file and apply it as the application wide style sheet. Qt does the rest 🙂

The users can trivially write rules that apply to classes of widgets such as QPushButton or QListView. If you give them the names of important widgets in the application documentation, then they can use id based selectors to apply styles to specific widgets as well. This results in a very robust theme system for any Qt application with just three lines of code. It doesn’t get much simpler than that.

Leave a Reply

Your email address will not be published. Required fields are marked *