The popular Qt framework has a very convenient UI style management mechanism - Qt Style Sheet. Thanks to which the style of widgets and windows can be set in a CSS-like form. The style can be stored both in the application resources and in the external file.We want to edit the style file and immediately see how it looks in any form of the application.
#ifndef STYLELOADER_H #define STYLELOADER_H #include <QObject> #include <QKeySequence> class StyleLoader: public QObject { Q_OBJECT public: static void attach(const QString& filename = defaultStyleFile(), QKeySequence key = QKeySequence("F5")); bool eventFilter(QObject *obj, QEvent *event); private: StyleLoader(QObject * parent, const QString& filename, const QKeySequence& key); void setAppStyleSheet(); static QString defaultStyleFile(); QString m_filename; QKeySequence m_key; }; #endif // STYLELOADER_H #include "StyleLoader.h" #include <QApplication> #include <QFile> #include <QKeyEvent> #include <QDebug> void StyleLoader::attach(const QString &filename, QKeySequence key) { StyleLoader * loader = new StyleLoader(qApp, filename, key); qApp->installEventFilter(loader); loader->setAppStyleSheet(); } bool StyleLoader::eventFilter(QObject *obj, QEvent *event) { if (event->type() == QEvent::KeyPress) { QKeyEvent *keyEvent = static_cast<QKeyEvent *>(event); if(m_key == QKeySequence(keyEvent->key())) setAppStyleSheet(); return true; } else return QObject::eventFilter(obj, event); } void StyleLoader::setAppStyleSheet() { QFile file(m_filename); if(!file.open(QIODevice::ReadOnly)) { qDebug() << "Cannot open stylesheet file " << m_filename; return; } QString stylesheet = QString::fromUtf8(file.readAll()); qApp->setStyleSheet(stylesheet); } QString StyleLoader::defaultStyleFile() { return QApplication::applicationDirPath() + "/style.qss"; } StyleLoader::StyleLoader(QObject *parent, const QString& filename, const QKeySequence &key): QObject(parent), m_filename(filename), m_key(key) { } StyleLoader::attach(); __ /style.qss ;F5 . StyleLoader::attach("c:/myStyle.qss", QKeySequence("F6")); Source: https://habr.com/ru/post/232323/
All Articles