官方提供的基礎指南三-訊號和槽
訊號和槽機制為對元件的事件進行繫結提供了靈活的的支援,簡化了GUI程式開發的方式。基本使用方式在上篇文章中已經涉及,這裡就不再敘述了。
前文中的語句:
button.clicked.connect(sayHello)
就是將button的clicked訊號,繫結到sayHello函式(槽)上。但這種方法,不能給槽函式傳遞任何引數。
可傳遞引數的槽函式定義方法
from PySide2.QtCore import Slot, QObject, Signal @Slot(str) def say_some_words(words): print(words) class Communicate(QObject): speak = Signal(str) someone = Communicate() someone.speak.connect(say_some_words) someone.speak.emit("Hello everybody!")
上述程式碼中:
1.使用Slot裝飾器修飾並定義了槽函式say_some_words()
2.繼承QObject類,並建立一個新的訊號speak,使其接受一個字串型別的引數。
3.例項化訊號類Communicate,並繫結槽函式至此類。
4.使用emit()方法引發訊號,從而呼叫槽函式。
可傳遞多種資料型別的槽函式和訊號的定義
import sys from PySide2.QtWidgets import QApplication, QPushButton from PySide2.QtCore import QObject, Signal, Slot app = QApplication(sys.argv) # define a new slot that receives a C 'int' or a 'str' # and has 'saySomething' as its name @Slot(int) @Slot(str) def say_something(stuff): print(stuff) class Communicate(QObject): # create two new signals on the fly: one will handle # int type, the other will handle strings speak_number = Signal(int) speak_word = Signal(str) someone = Communicate() # connect signal and slot properly someone.speak_number.connect(say_something) someone.speak_word.connect(say_something) # emit each 'speak' signal someone.speak_number.emit(10) someone.speak_word.emit("Hello everybody!")
與傳遞一種型別引數相比,槽函式定義時同時使用了兩個Slot裝飾器,在訊號定義時,定義了接受兩種不同型別引數的訊號。其他的基本上沒有什麼變化。
複雜訊號定義方式二
#槽函式定義與上例相同 class Communicate(QObject): speak = Signal((int,), (str,)) someone = Communicate() someone.speak.connect(say_something) someone.speak[str].connect(say_something) someone.speak.emit(10) someone.speak[str].emit("Hello everybody!")
這裡在訊號定義時使用不同的方式,訊號中引數為int時為預設引數,繫結和觸發採取相同的方式。而引數為str時,在繫結和觸發時,均應在訊號後新增型別標誌‘[str]’即可。
使用物件方法觸發訊號
class Communicate(QObject): speak = Signal() def __init__(self): super().__init__() self.speak.connect(self.say_hello) def speaking_method(self): self.speak.emit() def say_hello(self): print("Hello") someone = Communicate() someone.speaking_method()
這個也很容易理解,就是將訊號和觸發及繫結的函式都定義在類中。
當然,也可以應用functools.partial()呼叫的方式實現引數的傳遞。