减少 PyQt 应用程序的冗余代码

Reducing redundant code for a PyQt application

我还不够清晰,无法具体说明我的标题,但这基本上就是问题所在。我正在用 PyQt 制作一个 QGIS 插件。

脚本

class CreateSomething(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(CreateSomething, self).__init__(parent)
        self.setupUi(self)

        # Only select polygon layers in the layer combo box
        self.cmbLyrSelect.setFilters(QgsMapLayerProxyModel.PolygonLayer)
        # Emits a signal and connects to a function when layer is changed    
        self.cmbLyrSelect.layerChanged.connect(self.getLayerInfo)  

    # Function to get layer info if layer changed
    def getLayerInfo(self):
        # Selected/current layer in the combo box  
        currLyr = self.cmbLyrSelect.currentLayer()
        # Gets layer centroid
        lyrLoc = self.cmbLyrSelect.currentLayer().sourceExtent().center().toString(3)
        # Writes layer centroid to line edit
        self.linLyrLoc.setText(str(lyrLoc))
        # Populates combo box with fields of current layer
        self.cmbLyrFields.setLayer(currLyr)

如果插件是第一次打开,它不会填充必要的小部件,因为 cmbLyrSelect 小部件仅在用户更改图层时发出信号。

第一次打开

如果层被改变

解决方法 - 将 getLayerInfo 方法中的代码复制到 __init__ 方法中,以便在插件启动后填充小部件。

class CreateSomething(QtWidgets.QDialog, FORM_CLASS):
        def __init__(self, parent=None):
            """Constructor."""
            super(CreateSomething, self).__init__(parent)
            self.setupUi(self)

            self.cmbLyrSelect.setFilters(QgsMapLayerProxyModel.PolygonLayer)    
            self.cmbLyrSelect.layerChanged.connect(self.getLayerInfo)    
            currLyr = self.cmbLyrSelect.currentLayer()
            lyrLoc = self.cmbLyrSelect.currentLayer().sourceExtent().center().toString(3)
            self.linLyrLoc.setText(str(lyrLoc))
            self.cmbLyrFields.setLayer(currLyr)

在注册 LayerChanged 回调之前,只需在 __init__ 中显式调用一次 getLayerInfo

def __init__(self, parent=None):
    """Constructor."""
    super(CreateSomething, self).__init__(parent)
    self.setupUi(self)

    # Only select polygon layers in the layer combo box
    self.cmbLyrSelect.setFilters(QgsMapLayerProxyModel.PolygonLayer)
    # Explicitly get layer info on init
    self.getLayerInfo()
    # Emits a signal and connects to a function when layer is changed    
    self.cmbLyrSelect.layerChanged.connect(self.getLayerInfo)