16.2. 코드 조각

이 장에서는 플러그인 개발을 쉽게 할 수 있도록 도와주는 코드 조각(snippet)에 대해 설명합니다.

16.2.1. 단축키로 함수 메소드를 호출하는 방법

플러그인 내부의 initGui() 함수에 다음 코드를 추가하십시오.

self.key_action = QAction("Test Plugin", self.iface.mainWindow())
self.iface.registerMainWindowAction(self.key_action, "Ctrl+I")  # action triggered by Ctrl+I
self.iface.addPluginToMenu("&Test plugins", self.key_action)
self.key_action.triggered.connect(self.key_action_triggered)

unload() 함수에 다음 코드를 추가하십시오.

self.iface.unregisterMainWindowAction(self.key_action)

CTRL+I 단축키를 누르면 해당 메소드를 호출합니다.

def key_action_triggered(self):
  QMessageBox.information(self.iface.mainWindow(),"Ok", "You pressed Ctrl+I")

16.2.2. 레이어를 켜고 끄는 방법

범례에 있는 레이어에 접근할 수 있는 API가 있습니다. 다음은 활성화 레이어의 가시성을 켜고 끄는 예시입니다.

root = QgsProject.instance().layerTreeRoot()
node = root.findLayer(iface.activeLayer().id())
new_state = Qt.Checked if node.isVisible() == Qt.Unchecked else Qt.Unchecked
node.setItemVisibilityChecked(new_state)

16.2.3. 선택한 피처의 속성 테이블에 접근하는 방법

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
def change_value(value):
    """Change the value in the second column for all selected features.

    :param value: The new value.
    """
    layer = iface.activeLayer()
    if layer:
        count_selected = layer.selectedFeatureCount()
        if count_selected > 0:
            layer.startEditing()
            id_features = layer.selectedFeatureIds()
            for i in id_features:
                layer.changeAttributeValue(i, 1, value) # 1 being the second column
            layer.commitChanges()
        else:
            iface.messageBar().pushCritical("Error",
                "Please select at least one feature from current layer")
    else:
        iface.messageBar().pushCritical("Error", "Please select a layer")

# The method requires one parameter (the new value for the second
# field of the selected feature(s)) and can be called by
change_value(50)

16.2.4. 옵션 대화창에 있는 플러그인 용 인터페이스

Settings ► Options 에 사용자 지정 플러그인 옵션을 추가할 수 있습니다. 사용자 플러그인의 옵션을 위해 특정 주 메뉴 항목을 추가하는 것보다는 이 편이 좋은데, 모든 QGIS 응용 프로그램 설정과 플러그인 설정을 단일 위치에 모아두기 때문에 사용자가 설정을 찾고 탐색하기에 더 편하기 때문입니다.

다음 조각은 플러그인의 설정에 새로운 빈 탭만 추가할 것입니다. 사용자가 이 탭에 사용자 플러그인에 특화된 모든 옵션 및 설정을 채워 넣을 수 있습니다. 다음 클래스들을 서로 다른 파일로 분할할 수 있습니다. 이 예제에서 우리는 주 mainPlugin.py 파일 안에 클래스 2개를 추가할 것입니다.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
class MyPluginOptionsFactory(QgsOptionsWidgetFactory):

    def __init__(self):
        super().__init__()

    def icon(self):
        return QIcon('icons/my_plugin_icon.svg')

    def createWidget(self, parent):
        return ConfigOptionsPage(parent)


class ConfigOptionsPage(QgsOptionsPageWidget):

    def __init__(self, parent):
        super().__init__(parent)
        layout = QHBoxLayout()
        layout.setContentsMargins(0, 0, 0, 0)
        self.setLayout(layout)

마지막으로 가져온 것들을 추가하고 __init__ 함수를 수정합니다:

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
from qgis.PyQt.QtWidgets import QHBoxLayout
from qgis.gui import QgsOptionsWidgetFactory, QgsOptionsPageWidget


class MyPlugin:
    """QGIS Plugin Implementation."""

    def __init__(self, iface):
        """Constructor.

        :param iface: An interface instance that will be passed to this class
            which provides the hook by which you can manipulate the QGIS
            application at run time.
        :type iface: QgsInterface
        """
        # Save reference to the QGIS interface
        self.iface = iface


    def initGui(self):
        self.options_factory = MyPluginOptionsFactory()
        self.options_factory.setTitle(self.tr('My Plugin'))
        iface.registerOptionsWidgetFactory(self.options_factory)

    def unload(self):
        iface.unregisterOptionsWidgetFactory(self.options_factory)

벡터 레이어 속성 대화창에 사용자 지정 탭 추가

비슷한 논리를 적용해서 QgsMapLayerConfigWidgetFactoryQgsMapLayerConfigWidget 클래스를 사용하면 레이어 속성 대화창에 플러그인 사용자 지정 옵션을 추가할 수 있습니다.