I want to change my application Theme with QRadioButton
in the QWidget
application.
can anyone help me?
I have a Setting class that has some settings and one of them is changing the theme between dark and light.
it is a C++ app with OpenGL.
void Settings::on_DarkTheme_clicked()
{
}
void Settings::on_lightTheme_clicked()
{
}
what should I have to write in these 2 methods?
I used .qss file like this
int main(int argc, char *argv[])
{
QSurfaceFormat fmt;
fmt.setVersion(3,3);
fmt.setProfile(QSurfaceFormat::CoreProfile);
fmt.setSamples(8);
fmt.setOption(QSurfaceFormat::StereoBuffers);
fmt.setSwapBehavior(QSurfaceFormat::DoubleBuffer);
QSurfaceFormat::setDefaultFormat(fmt);
loadSettings();
App app(argc, argv);
QFile stylesheetFile("./Combinear.qss");
stylesheetFile.open(QFile::ReadOnly);
QString stylesheet = QLatin1String(stylesheetFile.readAll());
app.setStyleSheet(stylesheet);
MainWindow w;
w.show();
const auto returnValue = app.exec();
App::setFinished();
return returnValue;
}
but it didn't Work and I'm confused
First of all, I add a radioButton
in my mainwindow.ui
.
this is my mainwindow.h
:
#ifndef MAINWINDOW_H
#define MAINWINDOW_H
#include <QMainWindow>
QT_BEGIN_NAMESPACE
namespace Ui
{
class MainWindow;
}
QT_END_NAMESPACE
class MainWindow: public QMainWindow
{
Q_OBJECT
public:
MainWindow(QWidget *parent = nullptr);
~MainWindow();
signals:
void changedDark();
void changedLight();
private slots:
void on_radioButton_clicked(bool checked);
private:
Ui::MainWindow *ui;
};
#endif // MAINWINDOW_H
and my mainwindow.cpp
:
#include "mainwindow.h"
#include "ui_mainwindow.h"
MainWindow::MainWindow(QWidget *parent):
QMainWindow(parent),
ui(new Ui::MainWindow)
{
ui->setupUi(this);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_radioButton_clicked(bool checked)
{
if (checked)
{
ui->radioButton->setText("Dark");
emit changedDark();
}
else
{
ui->radioButton->setText("Light");
emit changedLight();
}
}
and my main.cpp:
#include "mainwindow.h"
#include <QApplication>
#include <QFile>
int main(int argc, char *argv[])
{
QApplication a(argc, argv);
MainWindow w;
w.show();
QObject::connect(&w, &MainWindow::changedDark, &a, [&]
{
/**
* Load the application style
*/
QFile dark_styleFile(":/theme/themes/MaterialDark.qss");
dark_styleFile.open(QFile::ReadOnly);
/**
* Apply the loaded stylesheet
*/
QString style(dark_styleFile.readAll());
a.setStyleSheet(style);
});
QObject::connect(&w, &MainWindow::changedLight, &a, [&]
{
/**
* Load the application style
*/
QFile light_styleFile(":/theme/themes/Ubuntu.qss");
light_styleFile.open(QFile::ReadOnly);
/**
* Apply the loaded stylesheet
*/
QString style(light_styleFile.readAll());
a.setStyleSheet(style);
});
return a.exec();
}
This is my result:
you can clone it from this repo: