【问题标题】:How to disconnect function from QAction?如何断开功能与 QAction 的连接?
【发布时间】:2017-03-08 09:54:27
【问题描述】:

我正在为 GIS 软件 QGIS 开发一个插件。我有一个QAction 图标,选中该图标后,只要切换其可见性,就会将组中的图层连接到功能。然后当它被取消选中时,它应该断开这些功能,但我收到一个错误:

Traceback (most recent call last):
  File "C:/Users/Me/.qgis2/python/plugins\Example\Example.py", line 248, in run
    layers.visibilityChanged.disconnect(print_one)            
TypeError: 'function' object is not connected

这是一个示例代码:

def run(self, checked):
    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup('Group')

    def print_one():
        print 'one'

    if checked == True:            
        for layers in group.children():
            layers.visibilityChanged.connect(print_one)            
    else:
        for layers in group.children():
            layers.visibilityChanged.disconnect(print_one)            

为什么信号没有断开?

我可以只使用layers.visibilityChanged.disconnect(),但这会断开所有信号,因此不符合我的兴趣。

【问题讨论】:

  • @FranciscoRaga - 虽然您链接到的帖子中的答案有效,但这个新问题是问为什么可以在@987654326 中连接@ 语句但不能在else 语句中断开。

标签: python qt4 qgis qaction


【解决方案1】:

对于我在 PyQt 手册中的理解,你应该这样尝试:

layers.disconnect(print_one)

但我不确定,遗憾的是我没有时间尝试...

【讨论】:

  • 感谢您的回答,不幸的是这会产生错误:TypeError: arguments did not match any overloaded call: QObject.disconnect(QObject, SIGNAL(), QObject, SLOT()): argument 1 has unexpected type 'function' QObject.disconnect(QObject, SIGNAL(), callable): argument 1 has unexpected type 'function'
  • 我的错,我不明白你想做什么。
  • 别担心,我只找到了解决方法,所以问题仍然悬而未决:)
【解决方案2】:

来自the documentation(强调我的):

断开连接([插槽])

断开一个或多个插槽与信号的连接。 如果插槽未连接到信号,则会引发异常,或者如果信号根本没有连接。

因此,您会收到一个异常,因为当您尝试断开它时,信号未连接到插槽。

作为一种解决方法:

if checked == True:            
    for layers in group.children():
        layers.visibilityChanged.connect(print_one)            
else:
    for layers in group.children():
        try:
            layers.visibilityChanged.disconnect(print_one) 
        except:
            pass

【讨论】:

  • 感谢您的回答,但这正是我之前尝试过的。显然没有出现错误,因为它正在传递,但由于某种原因它仍然没有断开插槽......
【解决方案3】:

我猜我找到了另一种方法,即包含一个 if 语句来检查 QAction 图标是否被选中,并将其放在 print_one() 函数中:

def run(self):
    root = QgsProject.instance().layerTreeRoot()
    group = root.findGroup('Group')

    def print_one():
        if self.plugin_icon.isChecked():
            print 'one'
        else:
            layers.visibilityChanged.disconnect(print_one)             

    for layers in group.children():
        layers.visibilityChanged.connect(print_one) 

仍然很好奇为什么我无法使用问题中显示的方法断开它,但与此同时,这可行。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-08-15
    • 1970-01-01
    • 1970-01-01
    • 2021-08-15
    • 2023-03-27
    • 1970-01-01
    相关资源
    最近更新 更多