Outdated version of the documentation. Find the latest one here.

設定の読み込みと保存

それは、何回もユーザーがプラグインの実行される次回の日時を入力したり、それらを再度選択する必要がないように、いくつかの変数を保存するためのプラグインのために便利です。

これらの変数は、QtとQGISのAPIを利用して取得し保存することができます。各変数には、ユーザーの好みの色のために、キー「favourite_color」またはその他の意味のある文字列を使用することができます。—変数にアクセスするために使用されるキーを選択する必要があります。これは、キーの名前にいくつかのストラクチャを与えることをお勧めします。

我々は、異なる種類の設定をすることができます:

  • global settings — they are bound to the user at particular machine. QGIS itself stores a lot of global settings, for example, main window size or default snapping tolerance. This functionality is provided directly by Qt framework by the means of QSettings class. By default, this class stores settings in system’s “native” way of storing settings, that is — registry (on Windows), .plist file (on Mac OS X) or .ini file (on Unix). The QSettings documentation is comprehensive, so we will provide just a simple example:

    def store():
      s = QSettings()
      s.setValue("myplugin/mytext", "hello world")
      s.setValue("myplugin/myint",  10)
      s.setValue("myplugin/myreal", 3.14)
    
    def read():
      s = QSettings()
      mytext = s.value("myplugin/mytext", "default text")
      myint  = s.value("myplugin/myint", 123)
      myreal = s.value("myplugin/myreal", 2.71)
    

The second parameter of the value() method is optional and specifies the default value if there is no previous value set for the passed setting name.

  • project settings — vary between different projects and therefore they are connected with a project file. Map canvas background color or destination coordinate reference system (CRS) are examples — white background and WGS84 might be suitable for one project, while yellow background and UTM projection are better for another one. An example of usage follows:

    proj = QgsProject.instance()
    
    # store values
    proj.writeEntry("myplugin", "mytext", "hello world")
    proj.writeEntry("myplugin", "myint", 10)
    proj.writeEntry("myplugin", "mydouble", 0.01)
    proj.writeEntry("myplugin", "mybool", True)
    
    # read values
    mytext = proj.readEntry("myplugin", "mytext", "default text")[0]
    myint = proj.readNumEntry("myplugin", "myint", 123)[0]
    

ご覧の通り writeEntry() メソッドがすべてのデータ型のために使われますが、いくつかのメソッドが後ろに設定値を読み込むために存在し、対応するものは各々のデータ型のために選ばなければなりません。

  • map layer settings — these settings are related to a particular instance of a map layer with a project. They are not connected with underlying data source of a layer, so if you create two map layer instances of one shapefile, they will not share the settings. The settings are stored in project file, so if the user opens the project again, the layer-related settings will be there again. This functionality has been added in QGIS v1.4. The API is similar to QSettings — it takes and returns QVariant instances:

    # save a value
    layer.setCustomProperty("mytext", "hello world")
    
    # read the value again
    mytext = layer.customProperty("mytext", "default text")