【问题标题】:How to connect PyQt signal to external function如何将 PyQt 信号连接到外部函数
【发布时间】:2016-10-13 17:18:06
【问题描述】:

如何将一个文件中的 pyqt 按钮信号连接到另一个 python 文件中的函数?我尝试了各种方法,但似乎没有任何效果。 这是第一个文件:

from PyQt4 import QtGui
from PyQt4.QtGui import QMainWindow
from MainUIFile import Ui_Main
from pythonfile import myOutsideFunction
class MainWindow(QMainWindow,Ui_file):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.btn.clicked.connect(myOutsideFunction())

第一个调用的第二个文件:

def myOutsideFunction(self):
    # Do some stuff here

我该怎么做呢?

【问题讨论】:

  • 我也有同样的问题。你最后解决了吗?
  • 我也遇到了同样的问题。我可以通过将函数放入 mixin 并让 MainWindow 从 mixin 继承来修复它(例如 class MainWindow(QMainWindow, EventsMixin)

标签: python windows file pyqt


【解决方案1】:

您当前正在调用myOutsideFunction 并将结果传递给connect 函数,该函数需要一个可调用对象作为参数。

在连接调用中从myOutsideFunction 中删除括号

self.btn.clicked.connect(myOutsideFunction)

【讨论】:

  • 在没有任何运气的情况下发布之前,我实际上已经在做没有括号的 .connect(myOutsideFunction) 了。感谢您的回复。
  • @user3419537。请注意,myOutsideFunction 有一个 self 参数。如果这是故意的,它可能会解释其他错误是什么......
【解决方案2】:

连接到代码之外的函数有什么重要性?你能不能只做这样的事情:

def myOutsideFunction(a,b,c,d):
    #process variables/objects a,b,c,d as you wish
    return answer

from PyQt4 import QtGui
from PyQt4.QtGui import QMainWindow
from MainUIFile import Ui_Main
from pythonfile import myOutsideFunction
class MainWindow(QMainWindow,Ui_file):
    def __init__(self):
        QMainWindow.__init__(self)
        self.setupUi(self)
        self.btn.clicked.connect(self.pressed_the_button())
        #initialize your variables/objects for your outside function if need be

    def pressed_the_button(self):
        answer_from_outside_function = myOutsideFunction(self.a,self.b,self.c,self.d)
        # run whatever you need to here...

【讨论】:

  • 这不是解决方案 - 它与问题中的代码完全相同。
  • @ekhumoro 你觉得怎么样?我们没有迹象表明实际的失败是什么。问题是如何将按钮连接到外部功能。这是一种方法。大概有人会将其他变量/对象传递给该外部函数,这可以通过在 init 或代码中的其他位置定义它们来完成。我已经编辑了我的答案,使其更具描述性。
  • 问题中的代码不起作用,因为它试图将可调用对象的返回值传递给connect,而不是可调用对象本身。您的代码犯了完全相同的错误。 other answer here 已经涵盖了这一点。
  • 我遇到了完全相同的问题,我认为这是因为myOutsideFunction 与 GUI 的线程不同,或者类似的线程。看来您要连接到信号的函数必须是您的类 MainWindow 的属性,或者是从与 GUI 相同的线程创建的对象的函数。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-11-01
  • 1970-01-01
  • 1970-01-01
  • 2013-12-31
  • 2016-11-03
相关资源
最近更新 更多