【问题标题】:Calling a variable in a separate method/function inside a class in a PyQt script在 PyQt 脚本中的类内的单独方法/函数中调用变量
【发布时间】:2022-01-05 02:00:48
【问题描述】:

我有这样的脚本

class CreateSomething(QtWidgets.QDialog, FORM_CLASS):
    def __init__(self, parent=None):
        """Constructor."""
        super(CreateSomething, self).__init__(parent)
        self.setupUi(self)
        # Activates the functions when the plugin is first opened
        self.getLayerInfo()
        self.anotherMethod()
        # Emits a signal and activates the function when the 
        # selected layer is changed
        self.cmbLyrSelect.layerChanged.connect(self.getLayerInfo) 
        # Same as above but when the field is changed
        self.cmbLyrFields.fieldChanged.connect(self.getLayerInfo)

    def getLayerInfo(self):
        # Stores the current layer, a QgsVectorLayer, in a variable
        currLyr = self.cmbLyrSelect.currentLayer()
        ...
    
    def anotherMethod(self):
        # Prints the layer name of the currently selected layer which is
        # stored in the currLyr variable in the previous method
        self.lineEdit.setText(currLyr.sourceName())

我已尝试多次将 currLyr 更改为 self.currLyr = self.cmbLyrSelect.currentLayer() 并将最后一行更改为 self.linTranslate.setText(self.currLyr.sourceName()) 但 Python 和 QGIS 都返回错误消息 "currLyr" is not defined

对于上下文,以下脚本有效,但我想为每个不同的任务单独创建一个方法。

def getLayerInfo(self):
    currLyr = self.cmbLyrSelect.currentLayer()
    self.lineEdit.setText(currLyr.sourceName())
    ...

【问题讨论】:

    标签: python class oop variables methods


    【解决方案1】:

    解决了!感谢本文中的第一个示例 https://www.geekpills.com/operating-system/linux/python-passing-variable-between-functions

    以下脚本现在可以按预期工作

    class CreateSomething(QtWidgets.QDialog, FORM_CLASS):
        def __init__(self, parent=None):
            """Constructor."""
            super(CreateSomething, self).__init__(parent)
            self.setupUi(self)
            self.getLayerInfo()
            self.anotherMethod() 
            self.cmbLyrSelect.layerChanged.connect(self.getLayerInfo) 
            self.cmbLyrFields.fieldChanged.connect(self.getLayerInfo)
    
        def getLayerInfo(self):
            currLyr = self.cmbLyrSelect.currentLayer()
            return currLyr # ADDED
            ...
        
        def anotherMethod(self):
            currLyr = self.getLayerInfo() # ADDED
            self.lineEdit.setText(currLyr.sourceName())
    

    【讨论】:

      猜你喜欢
      • 2017-05-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-11-21
      • 1970-01-01
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多