减少 PyQt 应用程序的冗余代码
Posted
技术标签:
【中文标题】减少 PyQt 应用程序的冗余代码【英文标题】:Reducing redundant code for a PyQt application 【发布时间】:2021-12-30 20:06:25 【问题描述】:我还不够清晰,无法具体说明我的标题,但这基本上就是问题所在。我正在用 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)
【问题讨论】:
【参考方案1】:在注册 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)
【讨论】:
以上是关于减少 PyQt 应用程序的冗余代码的主要内容,如果未能解决你的问题,请参考以下文章