1、在配置文件里增加两个qss文件
第一个是深蓝色主题,第二个是亮色主题
ps:设置背景图
QWidget#centralWidget{
border: 0px solid #7D7D7D;
background: rgba(0,0,0,0);
background-image:url(:/main/back.png)
}
2、新建主题选择类
ps:
主要是一个界面类,初始化时将当前文件里里所有的主题列在表格里,供用户选择;
需要传入当前主程序的this指针,通过this->setStyleSheet来设置qss;
在每次设置主题之后需要把当前主题存到配置文件,下次启动程序自动设置为上次已设置的主题。
Ztheme.h
#ifndef ZTHEME_H
#define ZTHEME_H
#include <QDialog>
namespace Ui {
class Ztheme;
}
namespace ZTHEME_NAMESPACE {
const QString DEFAULE_THEME_NAME = "main_dark_blue.qss";
const QString THEMES_DIR = "./themes/";
}
class Ztheme : public QDialog
{
Q_OBJECT
public:
explicit Ztheme(QWidget *parent = 0);
~Ztheme();
/*传入需要设置的程序的指针*/
inline void setMainUi(QWidget* p){this->pParent = p;}
/*设置上次的风格*/
void setLastTheme();
public:
static QWidget* pParent;
private slots:
void on_pushButton_submit_clicked();
void on_pushButton_cancel_clicked();
private:
Ui::Ztheme *ui;
void initThemes(void);
};
#endif // ZTHEME_H
Ztheme.cpp
#include "ztheme.h"
#include "ui_ztheme.h"
#include <QDir>
#include <QFile>
#include <QDebug>
#include "config.h"
using namespace ZTHEME_NAMESPACE;
using namespace ZConfigNamespace;
QWidget* Ztheme::pParent = nullptr;
Ztheme::Ztheme(QWidget *parent) :
QDialog(parent),
ui(new Ui::Ztheme)
{
ui->setupUi(this);
(void)initThemes();
}
Ztheme::~Ztheme()
{
delete ui;
}
void Ztheme::setLastTheme()
{
QByteArray themeBa;
QString themePath = QDir::currentPath() + "/themes/" + Config::getInstance()->getCfgItemByKey(CUR_THEME).toString();
QFile file(themePath);
file.open(QFile::ReadOnly);
if(file.isOpen()){
themeBa = file.readAll();
file.close();
}
if(pParent){
this->pParent->setStyleSheet(themeBa);
}
}
void Ztheme::initThemes()
{
ui->tableWidget_theme->clearContents();
ui->tableWidget_theme->setRowCount(0);
QDir dir(THEMES_DIR);
QFileInfoList file_list = dir.entryInfoList(QDir::Files | QDir::Hidden | QDir::NoSymLinks);
for(int i=0; i<file_list.size(); i++)
{
ui->tableWidget_theme->insertRow(ui->tableWidget_theme->rowCount());
ui->tableWidget_theme->setItem(ui->tableWidget_theme->rowCount()-1, 0, new QTableWidgetItem(QString::number(ui->tableWidget_theme->rowCount())));
ui->tableWidget_theme->setItem(ui->tableWidget_theme->rowCount()-1, 1, new QTableWidgetItem(file_list.at(i).baseName()));
for(int col=0; col<2; col++){
ui->tableWidget_theme->item(ui->tableWidget_theme->rowCount()-1, col)->setTextAlignment(Qt::AlignHCenter|Qt::AlignVCenter);
}
}
}
void Ztheme::on_pushButton_submit_clicked()
{
QByteArray themeBa;
QString qssFileName = ui->tableWidget_theme->item(ui->tableWidget_theme->currentRow(), 1)->text();
QString themePath = THEMES_DIR + qssFileName + ".qss";
QFile file(themePath);
file.open(QFile::ReadOnly);
if(file.isOpen()){
themeBa = file.readAll();
}
if(pParent){
this->pParent->setStyleSheet(themeBa);
Config::getInstance()->setValue(qssFileName + ".qss" ,CUR_THEME);
}
this->done(1);
}
void Ztheme::on_pushButton_cancel_clicked()
{
this->done(0);
}
Ztheme.ui
综上:核心就是设置qss文件