从从 GLib 2.26 起增加了GSettings组件,便于编写程序的设置参数。据说比GConf快很多,许多GNOME程序都开始使用它了。使用它的话需要先编写一个名字以gschema.xml结尾的文件,将需要的设置项设置好,最后使用glib-compile-schemas来编译成二进制文件。
<schemalist>
<schema id="com.iltgcl.gtkmmsample" path="/com/iltgcl/gtkmmsample/" >
<key name="toolbar-visible" type="b">
<default>true</default>
<summary>Is the toolbar showing?</summary>
<description>
Show or hide the toolbar.
</description>
</key>
<key name="statusbar-visible" type="b">
<default>true</default>
<summary>Is the statusbar showing?</summary>
<description>
Show or hide the statusbar.
</description>
</key>
<key name="window-state" type="i">
<default>0</default>
<summary>window's state</summary>
<description>
The state of main window.
</description>
</key>
<key name="window-width" type="i">
<default>800</default>
<summary>window's width</summary>
<description>
The width of main window.
</description>
</key>
<key name="window-height" type="i">
<default>500</default>
<summary>window's height</summary>
<description>
The height of main window.
</description>
</key>
</schema>
</schemalist>
程序中使用就很简单了,先初始化
m_refSettings = Gio::Settings::create("com.iltgcl.gtkmmsample");
然后获取和设置分别如下:
m_refSettings->get_int(KEY_WINDOW_STATE);
m_refSettings->set_int(KEY_WINDOW_STATE, state);
将所有的参数全部放到一个schema里,不便于程序的扩展,也使得程序比较凌乱。可以采用层次的结构来组织,最终的schema文件如下:
<schemalist>
<schema id="com.iltgcl.gtkmmsample" path="/com/iltgcl/gtkmmsample/">
<child schema="com.iltgcl.gtkmmsample.preferences" name="preferences"/>
<child schema="com.iltgcl.gtkmmsample.state" name="state"/>
</schema>
<schema id="com.iltgcl.gtkmmsample.preferences" path="/com/iltgcl/gtkmmsample/preferences/">
<child schema="com.iltgcl.gtkmmsample.preferences.ui" name="ui"/>
</schema>
<schema id="com.iltgcl.gtkmmsample.preferences.ui" path="/com/iltgcl/gtkmmsample/preferences/ui/">
<key name="toolbar-visible" type="b">
<default>true</default>
<summary>Is the toolbar showing?</summary>
<description>Show or hide the toolbar.</description>
</key>
<key name="statusbar-visible" type="b">
<default>true</default>
<summary>Is the statusbar showing?</summary>
<description>Show or hide the statusbar.</description>
</key>
</schema>
<schema id="com.iltgcl.gtkmmsample.state" path="/com/iltgcl/gtkmmsample/state/">
<child schema="com.iltgcl.gtkmmsample.state.window" name="state"/>
</schema>
<schema id="com.iltgcl.gtkmmsample.state.window" path="/com/iltgcl/gtkmmsample/state/window/">
<key name="state" type="i">
<default>0</default>
</key>
<key name="width" type="i">
<default>800</default>
</key>
<key name="height" type="i">
<default>500</default>
</key>
</schema>
</schemalist>
这样以后扩展就比较容易了,当然代码中初始化的时候就需要改成:
m_refPrefUI = Gio::Settings::create("com.iltgcl.gtkmmsample.preferences.ui");
m_refWinState = Gio::Settings::create("com.iltgcl.gtkmmsample.state.window");
最后别忘了使用glib-compile-schemas来重新编译一下二进制文件