[英]Calling a variable in a separate method/function inside a class in a PyQt script
I have a script like this我有这样的脚本
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())
I've tried multiple changing currLyr to self.currLyr = self.cmbLyrSelect.currentLayer()
and the last line to self.linTranslate.setText(self.currLyr.sourceName())
but both Python and QGIS return an error saying "currLyr" is not defined
.我已经尝试多次将 currLyr 更改为
self.currLyr = self.cmbLyrSelect.currentLayer()
并将最后一行更改为self.linTranslate.setText(self.currLyr.sourceName())
但 Python 和 QGIS 都返回错误"currLyr" is not defined
。
For context, the following script works but I want to separate create a method for each different task.对于上下文,以下脚本有效,但我想为每个不同的任务单独创建一个方法。
def getLayerInfo(self):
currLyr = self.cmbLyrSelect.currentLayer()
self.lineEdit.setText(currLyr.sourceName())
...
Solved!解决了! Thanks to the first example in this article https://www.geekpills.com/operating-system/linux/python-passing-variable-between-functions
感谢本文中的第一个示例https://www.geekpills.com/operating-system/linux/python-passing-variable-between-functions
The following script now works as intended以下脚本现在按预期工作
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())
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.