2. 프로젝트 불러오기

힌트

여러분이 PyQGIS 콘솔을 사용하지 않는 경우 이 페이지에 있는 코드 조각들을 다음과 같이 가져와야 합니다:

1from qgis.core import (
2    Qgis,
3    QgsProject,
4    QgsPathResolver
5)
6
7from qgis.gui import (
8    QgsLayerTreeMapCanvasBridge,
9)

플러그인으로부터 기존 프로젝트를, 또는 (더 자주) 독립 설치형 QGIS 파이썬 응용 프로그램을 개발할 때, 기존 프로젝트를 불러와야 하는 경우가 많습니다. (파이썬 응용 프로그램 참조)

현재 QGIS 응용 프로그램으로 프로젝트를 불러오려면 QgsProject 클래스의 인스턴스를 생성해야 합니다. 이 클래스는 싱글턴(singleton) 클래스이기 때문에, 생성하려면 이 클래스의 instance() 메소드를 사용해야만 합니다. 이 클래스의 read() 메소드를 호출해서 불러올 프로젝트의 경로를 넘겨줄 수 있습니다:

 1# If you are not inside a QGIS console you first need to import
 2# qgis and PyQt classes you will use in this script as shown below:
 3from qgis.core import QgsProject
 4# Get the project instance
 5project = QgsProject.instance()
 6# Print the current project file name (might be empty in case no projects have been loaded)
 7# print(project.fileName())
 8
 9# Load another project
10project.read('testdata/01_project.qgs')
11print(project.fileName())
testdata/01_project.qgs

프로젝트를 (예를 들어 몇몇 레이어를 추가하거나 제거하기 위해) 수정하고 변경 사항을 저장해야 한다면, 프로젝트 인스턴스의 write() 메소드를 호출하십시오. write() 메소드도 프로젝트를 새 위치에 저장하기 위한 선택적인 경로를 입력받습니다.

# Save the project to the same
project.write()
# ... or to a new file
project.write('testdata/my_new_qgis_project.qgs')

read()write() 두 함수 모두 작업 수행이 성공적이었는지 확인할 수 있는 불(boolean) 값을 반환합니다.

참고

QGIS 독립 설치형 응용 프로그램을 작성하고 있는 경우, 불러온 프로젝트를 캔버스와 동기화시키려면 다음 예시에서처럼 QgsLayerTreeMapCanvasBridge 클래스의 인스턴스를 생성해야 합니다:

bridge = QgsLayerTreeMapCanvasBridge( \
         QgsProject.instance().layerTreeRoot(), canvas)
# Now you can safely load your project and see it in the canvas
project.read('testdata/my_new_qgis_project.qgs')

2.1. 경로 오류 해결하기

It can happen that layers loaded in the project are moved to another location. When the project is loaded again all the layer paths are broken. The QgsPathResolver class helps you rewrite layers path within the project.

Its setPathPreprocessor() method allows setting a custom path pre-processor function to manipulate paths and data sources prior to resolving them to file references or layer sources.

The processor function must accept a single string argument (representing the original file path or data source) and return a processed version of this path. The path pre-processor function is called before any bad layer handler. If multiple preprocessors are set, they will be called in sequence based on the order in which they were originally set.

다음은 몇몇 활용 사례입니다:

  1. 변경된 경로를 대체:

    def my_processor(path):
        return path.replace('c:/Users/ClintBarton/Documents/Projects', 'x:/Projects/')
    
    QgsPathResolver.setPathPreprocessor(my_processor)
    
  2. 새 데이터베이스 호스트 주소로 대체:

    def my_processor(path):
        return path.replace('host=10.1.1.115', 'host=10.1.1.116')
    
    QgsPathResolver.setPathPreprocessor(my_processor)
    
  3. 저장된 데이터베이스 인증 정보를 새 정보로 대체:

    1def my_processor(path):
    2    path= path.replace("user='gis_team'", "user='team_awesome'")
    3    path = path.replace("password='cats'", "password='g7as!m*'")
    4    return path
    5
    6QgsPathResolver.setPathPreprocessor(my_processor)
    

Likewise, a setPathWriter() method is available for a path writer function.

An example to replace the path with a variable:

def my_processor(path):
  return path.replace('c:/Users/ClintBarton/Documents/Projects', '$projectdir$')

QgsPathResolver.setPathWriter(my_processor)

Both methods return an id that can be used to remove the pre-processor or writer they added. See removePathPreprocessor() and removePathWriter().

2.2. Using flags to speed up things

In some instances where you may not need to use a fully functional project, but only want to access it for a specific reason, flags may be helpful. A full list of flags is available under ProjectReadFlag. Multiple flags can be added together.

As an example, if we do not care about actual layers and data and simply want to access a project (e.g. for layout or 3D view settings), we can use DontResolveLayers flag to bypass the data validation step and prevent the bad layer dialog from appearing. The following can be done:

readflags = Qgis.ProjectReadFlags()
readflags |= Qgis.ProjectReadFlag.DontResolveLayers
project = QgsProject()
project.read('C:/Users/ClintBarton/Documents/Projects/mysweetproject.qgs', readflags)

To add more flags the python Bitwise OR operator (|) must be used.