QBO层插件(QBO)

2024-09-30 10:36:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图创建一个函数,根据在QComboBox中选择的项声明变量。这是一个QGIS 2.0和2.2的插件。我得到一个“列表索引超出范围”错误,但不知道为什么。我想知道我的combobox.currentIndex()没有给我我我想的那样。如果是这样的话,我想知道是否应该在程序运行之前找到一种方法将组合框的索引设置为默认值。在

#connecting the combo boxes to function
def initGui(self):
    QObject.connect(self.dlg.ui.indivCombo,SIGNAL("currentIndexChanged(int)"),self.layerChanged)
    QObject.connect(self.dlg.ui.grosCombo,SIGNAL("currentIndexChanged(int)"),self.layerChanged)
    QObject.connect(self.dlg.ui.resCombo,SIGNAL("currentIndexChanged(int)"),self.layerChanged)

#function to set my layer parameter to the equal the item at index chosen
def layerChanged(self):
    self.layerMap = QgsMapLayerRegistry.instance().mapLayers().values()
    self.indivLayer = self.layerMap[self.dlg.ui.indivCombo.currentIndex()]
    self.grosLayer = self.layerMap[self.dlg.ui.grosCombo.currentIndex()]
    self.resLayer = self.layerMap[self.dlg.ui.resCombo.currentIndex()]

#populating combo box with layers in stack
def run(self):
    # show the dialog
    self.dlg.show()
    for layer in self.iface.legendInterface().layers():
        if layer.type() == QgsMapLayer.VectorLayer:
            self.dlg.indivCombo.addItem(layer.name())
            self.dlg.grosCombo.addItem(layer.name())
            self.dlg.resCombo.addItem(layer.name())
    # Run the dialog event loop
    result = self.dlg.exec_()
    # See if OK was pressed
    if result == 1:
        pass

多亏了下面的答案,我现在对代码做了一些修改。layerChanged()现在使用identifiers方法,run()根据线程http://lists.osgeo.org/pipermail/qgis-developer/2010-November/011505.html的思想将层添加到组合框中。不过,这两个领域都给我带来了问题。”对于前者,None-type对象没有属性mapLayer”,对于后者,没有“Syntax error”属性。在

^{pr2}$

Tags: thetoselflayeruisignaldefconnect
2条回答

以您在面值上发布的示例代码为例,我可以看到几个问题。在

首先,根据initGui和{}方法的不同,可能有两组组合框在使用。这些信号连接到self.dlg.ui.*Combo,而项目被添加到self.dlg.*Combo。在

第二,你似乎是一次又一次地填充组合框,而没有事先清除它们。在

第三,您似乎没有保留组合框索引和列表之间的一对一关系,因为您是根据类型过滤层。在

最后,层的列表来自于amap的值,所以肯定不能保证它们会以相同的顺序出现。在

我建议您将layer id与每个组合项相关联,然后通过mapLayer方法检索层。也就是说,添加如下组合项:

    self.dlg.indivCombo.addItem(layer.name(), layer.id())

然后像这样检索图层:

^{pr2}$

注意:如果您使用Python2,组合数据将存储为QVariant,因此您需要像这样提取标识符:

    identifier = self.dlg.ui.indivCombo.itemData(index).toString()

或者这个:

    identifier = self.dlg.ui.indivCombo.itemData(index).toPyObject()

多亏了@ekhurvo的帮助,这项工作现在起作用了。只有在layerChanged()中对answer的建议进行了更改:

def layerChanged(self):
    registry = QgsMapLayerRegistry.instance()
    identifier = str(self.dlg.ui.indivCombo.itemData(self.dlg.ui.indivCombo.currentIndex()))
    self.indivLayer = registry.mapLayer(identifier)

这解决了一个问题,所选的索引混淆和不正确的多个组合框。在

相关问题 更多 >

    热门问题