作者:虚幻私塾
早餐店不会开到晚上,想吃的人早就来了!😄
一、换肤功能的后台实现
定义changeBackground
函数,让qml去调用这个函数来实现换肤功能,
函数的实现调用了setBackGround
函数:
//改变并储存背景
void MYPlay::changeBackground(QString url)
{
setBackGround(url);
}
setBackGround
函数实现如下:
void MYPlay::setBackGround(QString url)
{
QSettings *settingIni = new QSettings("setting.ini",QSettings::IniFormat);
QString backGroundpath = settingIni->value("Path/Background").toString();
if(url == NULL)
{
if(backGroundpath == NULL)
{
delete settingIni;
return;
}
else
{
m_strBackgroundPath = backGroundpath;
QFileInfo fileInfo(backGroundpath);
m_strBackGroundChoosePath = fileInfo.path();
qDebug()<<m_strBackGroundChoosePath<<endl;
delete settingIni;
emit backGroundChanged(m_strBackgroundPath);
emit backGroundChooseChanged(m_strBackGroundChoosePath);
return;
}
}
if(m_strBackgroundPath != url)
{
settingIni->setValue("Path/Background",url);
m_strBackgroundPath = url;
QFileInfo fileInfo(url);
//qDebug()<<fileInfo.suffix();
m_strBackGroundChoosePath = fileInfo.path();
emit backGroundChanged(m_strBackgroundPath);
emit backGroundChooseChanged(m_strBackGroundChoosePath);
}
delete settingIni;
}
QSetting
函数写一个setting.ini
的文件来设置路径。
每一次传递过来的路径我们都将它保存下来,
QSettings *settingIni = new QSettings("setting.ini",QSettings::IniFormat);
从配置文件读取数据:
QString backGroundpath = settingIni->value("Path/Background").toString();
如果传递过来的url为空
- 如果读取到的数据为空,那么只需要直接将内存释放掉然后return,、
- 如果读取到内容,就将图片加载过来,通过emit,发送信号到ui层改变数值
if(url == NULL) { if(backGroundpath == NULL) { delete settingIni; return; } else { m_strBackgroundPath = backGroundpath; QFileInfo fileInfo(backGroundpath); m_strBackGroundChoosePath = fileInfo.path(); qDebug()<<m_strBackGroundChoosePath<<endl; delete settingIni; emit backGroundChanged(m_strBackgroundPath); emit backGroundChooseChanged(m_strBackGroundChoosePath); return; } }
如果传递过来的url
不为空,并且和当前路径不一样,就需要设置setting.ini
的文件数据, 成员变量都设置为传递过来的url
,最后,同样 发送修改的信号
if(m_strBackgroundPath != url)
{
settingIni->setValue("Path/Background",url);
m_strBackgroundPath = url;
QFileInfo fileInfo(url);
//qDebug()<<fileInfo.suffix();
m_strBackGroundChoosePath = fileInfo.path();
emit backGroundChanged(m_strBackgroundPath);
emit backGroundChooseChanged(m_strBackGroundChoosePath);
}
怎么会调用到这里的设置代码呢,上节课已经讲解过了,在qml
的onAccepted
中调用了:
onAccepted: {
console.log(backGround.source)
backGround.source = chooseSkin.fileUrl;
myplay.changeBackground(chooseSkin.fileUrl.toString().substring(8,chooseSkin.fileUrl.length))
console.log("You chose: " + chooseSkin.fileUrl);
}
通过调用substring提取字符串,去除前缀"file:///"
substring(8,chooseSkin.fileUrl.length))
运行程序可以发现换肤功能可以正常运行,并且我们看到配置文件setting.ini
也被修改了。
二、总结
- 关于换肤功能的前台和后台都已经完全实现了。
- QT的ui部分有很多地方要处理,后面我们可能就会讲解一些关键知识点,大家有时间自己研究ui这一块的源码。