头文件:style_helper.h
#pragma once
#include<QEvent>
#include<QMouseEvent>
#include<QPushButton>
#include<QToolButton>
#include<QGraphicsItem>
#include<QtXml/QtXml>
#include<QtWidgets/QGraphicsView>
class StyleHelper : public QObject{
public:
StyleHelper(QObject* pParent = Q_NULLPTR);
virtual ~StyleHelper();
public:
void openIniFile(const QString& fileName);
public:
QString getValue(const QString& prefix,const QString& key) const;
QColor getColor(const QString& prefix,const QString& key,QColor color=QColor()) const;
int getInteger(const QString& prefix,const QString& key,int val) const;
proteced:
QSettings* settings_;
};
源文件:style.helper.cpp
#include "style_hepler.h"
StyleHelper::StyleHelper(QObject* parent)
: QObject(parent)
, settings_(Q_NULLPTR){
}
StyleHelper::StyleHelper(){
delete settings_;
}
void StyleHelper::openIniFile(const QString& fileName){
Q_ASSERT(!fileName.isEmpty());
if(fileName.isEmpty())
return;
if(settings_!=Q_NULLPTR)
delete settings_;
setting_=new Qsettings(fileName,QSettings::IniFormat);
Q_ASSERT(settings_->status()==QSetting::NoError);
settings_->sync();
settings_->setFallbacksEnabled(true);
}
QString StyleHelper::getValue(const QString& prefix,const QString& key) const{
Q_ASSERT(settings_!=Q_NULLPTR);
Qstring strValue;
settings_->beginGroup(prefix);
QVariant value=settings_->value(key);
if(value.isValid()&&value.type()==QVariant::String)
strValue=vlaue.toString();
settings_->endGroup();
return strValue;
}
QColor StyleHelper::getColor(const QString& prefix,const QString& key,QColor color) const{
Q_ASSERT(settings_!=Q_NULLPTR);
int r=0,g=0,b=0,a=255;
QString strValue=getValue(prefix,key);
if(!strValue.isEmpty()){
QStringList strList=strValue.split(' ');
if(strList.size()==3){
r=strList[0].toUInt();
g=strList[1].toUInt();
b=strList[2].toUInt();
}
else if(strList.size()==4){
r=strList[0].toUInt();
g=strList[1].toUInt();
b=strList[2].toUInt();
a=strList[3].toUInt();
}
returun QColor(r,g,b,a);
}
return color;
}
int StyleHelper::getInteger(const QString& prefix,const QString& key,int val) const{
Q_ASSERT(settings_!=Q_NULLPTR);
QString strValue=getValue(prefix,key);
if(!strValue.isEmpty())
val=strValue.toInt();
return val;
}
使用方法:
所需读样式的文件的头文件
#inlcude "style_helper.h"
class StyleHelper;
class 类名{
public:
StyleHelper helper_;
}
所需读样式的文件的源文件
void 类名::函数名(参数){
helper_.openIniFile(QString类型的需要打开的文件名);
QColor color_name1=helper_.getColor("Title","TitTextColor1");
QColor color_name2=helper_.getColor("Title","TitTextColor2");
}
ini文件内容
[Title]
TitTextColor1=0 0 0
TitTextColor2=255 255 255