在PyQt脚本中的类内的单独方法/函数中调用变量



我有一个类似的脚本

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())
...

已解决!感谢本文中的第一个示例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())

最新更新