[英]PyQt5: How do I “collect” or “receive” an emitted signal?
在我的代碼中,我在 2 個單獨的文件中有 2 個類。 我有一個信號testSignal
,一個按鈕pushButton
,我像這樣連接按鈕:
testSignal = QtCore.pyqtSignal()
pushButton.pressed.connect(buttonPressed)
def buttonPressed(self):
testSignal.emit()
現在我想要做的是“接收”類/文件中發出的信號,但我對 emit() 的實際工作原理有些不知所措。 有沒有人有任何關於 emit() function 指南的鏈接或者可以以某種方式提供幫助?
謝謝
[Py]Qt 信號必須在 class 級別聲明,因為它們只有在創建新的 class 實例時才會“激活”。 此外,它們只能用於從 QObject 繼承的類(包括 QWidget 子類),並且將它們與標准 python object
類一起使用將不起作用。
class SomeWindow(QtWidgets.QWidget):
testSignal = QtCore.pyqtSignal()
def __init__(self):
super().__init__()
# ...
pushButton.pressed.connect(self.buttonPressed)
# connect the custom signal with an *instance method*
self.testSignal.connect(self.someInstanceFunction)
def buttonPressed(self):
# emit the signal
self.testSignal.emit()
def someInstanceFunction(self):
print('hello from the instance!')
def someAnonymousFunction():
print('hello from outside!')
if __name__ == '__main__':
import sys
app = QtWidgets.QApplication(sys.argv)
window = SomeWindow()
# connect the signal with an anonymous function
window.testSignal.connect(someAnonymousFunction)
sys.exit(app.exec_())
顯然,上面的示例沒有多大意義,因為自定義信號通常用於在(可能不同的)類的實例之間進行通信,但這僅用於解釋目的。 此外,您可以“連接”信號(只要它們的簽名兼容):
class SomeWindow(QtWidgets.QWidget):
testSignal = QtCore.pyqtSignal()
def __init__(self):
super().__init__()
# ...
# emit the testSignal when the button emits its pressed signal
pushButton.pressed.connect(self.testSignal)
self.testSignal.connect(self.someInstanceFunction)
# ...
請注意,如果您想在用戶單擊按鈕時執行某些操作,則應該使用clicked()
,而不是pressed()
,並且區別非常重要:通常的約定是,僅當用戶按下按鈕時才認為按鈕被單擊並且在按鈕區域內釋放鼠標按鈕,這樣可以避免在按鈕區域外釋放鼠標按鈕時“點擊”。 如果您連接到pressed()
,只要鼠標按鈕按下按鈕,就會發出信號,這不被認為是標准行為。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.