官术网_书友最值得收藏!

Storing and reading project preferences

The QGIS application settings are stored using the Qt API. However, QGIS project settings have their own object. In this recipe, we'll set and read the project title and then set and read a custom preference for a plugin.

Getting ready

We are going to set a plugin preference using the sample plugin created in the previous recipe, Creating a QGIS plugin. You can substitute the name of any plugin you want, however. We will also run this recipe in the QGIS Python console for quick testing, but this code will normally be used in a plugin.

How to do it…

In this recipe, we will first write and then read the title of the current project. Then, we will create a custom value for a plugin called splash, which can be used for the plugin startup splash screen if desired.

  1. Start QGIS.
  2. From the Plugins menu, select Python Console.
  3. In the console, run the following code:
    proj = QgsProject.instance()
    proj.title("My QGIS Project")
    proj.title()
    proj.writeEntry("MyPlugin", "splash", "Geospatial Python Rocks!")
    proj.readEntry("MyPlugin", "splash", "Welcome!")[0]

How it works…

In the first two lines, we change the title of the current active project and then echo it back. In the next set of two lines, we set up and read custom settings for a plugin. Notice that the readEntry() method returns a tuple with the desired text and a boolean, acknowledging that the value is set. So, we extract the first index to get the text. The read method also allows the default text in case that property is not set (rather than throw an exception which must be handled) as well as the boolean value False to inform you that the default text was used because the property was not set. The values you set using this method are stored in the project's XML file when you save it.

There's more…

The QgsProject object has a number of methods and properties that may be useful. The QGIS API documentation details all of them at http://qgis.org/api/2.6/classQgsProject.html.

主站蜘蛛池模板: 静宁县| 玉溪市| 故城县| 平潭县| 涞源县| 遂宁市| 巨野县| 隆德县| 屏山县| 呼玛县| 佛教| 德兴市| 碌曲县| 梨树县| 龙州县| 留坝县| 乌鲁木齐县| 崇阳县| 东兴市| 武定县| 平湖市| 凤山县| 西林县| 梅州市| 个旧市| 乐都县| 明水县| 岢岚县| 泰来县| 镶黄旗| 准格尔旗| 洪洞县| 义乌市| 南平市| 宁国市| 当阳市| 海盐县| 吉林省| 阿拉善右旗| 康乐县| 惠东县|