有两个小部件:按钮和标签。 按下按钮时,我想运行标签的myFunction()方法。 如何使用信号和插槽实现这一目标?以下示例不起作用。
from PyQt import QtCore, QtGui
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
self.show()
def myFunction(self, arg=None):
print '...myFunction: received arg =', arg
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.click)
self.show()
def click(self):
print 'emitted'
self.emit(QtCore.SIGNAL('buttonClicked'))
lbl = label()
btn = button()
答案 0 :(得分:1)
一种解决方案是使用全局声明的QObject
变量connector
。我们使用connector.signal
:发出信号并连接要在signal.emit()上执行的方法。
从第一个小部件发出:connector.signal.emit()
连接第二个小部件的方法:connector.signal.connect(self.myFunction)
from PySide import QtCore, QtGui
class Communicate(QtCore.QObject):
signal = QtCore.Signal(str)
connector=Communicate()
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
connector.signal.connect(self.labelFunction)
self.show()
def labelFunction(self, arg=None):
print '...labelFunction: arg =', arg
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.click)
self.show()
def click(self):
connector.signal.emit("Hello World")
lbl = label()
btn = button()
我们可以通过传递label.labelFunction
作为回调参数来实现相同的功能。按钮的connector
将连接到它:
from PySide import QtCore, QtGui
class Communicate(QtCore.QObject):
signal = QtCore.Signal(str)
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
self.show()
def labelFunction(self, arg=None):
print '...labelFunction: arg = %s'%arg
class button(QtGui.QPushButton):
def __init__(self, callback=None, parent=None):
super(button, self).__init__(parent)
self.callback=callback
self.clicked.connect(self.click)
self.show()
def click(self):
connector=Communicate()
connector.signal.connect(self.callback)
connector.signal.emit("Hello World")
lbl = label()
btn = button(callback=lbl.labelFunction)
就像之前我们仍然在button.clicked上发出一样。
但是使用不同的语法将label
连接到customSignal
:
self.connect(btn, QtCore.SIGNAL('customSignal'), Function)
from PySide import QtCore, QtGui
def Function(arg=None):
print 'Function.arg: %r'%arg
class button(QtGui.QPushButton):
def __init__(self, parent=None):
super(button, self).__init__(parent)
self.clicked.connect(self.click)
self.show()
def click(self):
self.emit(QtCore.SIGNAL('customSignal'), 'String Arument')
btn = button()
class label(QtGui.QLabel):
def __init__(self, parent=None):
super(label, self).__init__(parent)
self.connect(btn, QtCore.SIGNAL('customSignal'), Function)
self.show()
lbl = label()