PySide QtCore.Signal幫助手冊

作者: meegoq.com  來源: MeeGo中文論壇-米趣網  發布時間: 2011-01-31 13:00  閱讀: 4148 次  推薦: 0   原文鏈接   [收藏]  

  本文主要是翻譯了Signal的文檔,感興趣的同學,可以參見 PySide的官方文檔。翻譯不足之處,還請指正。

  函數用法

 

 
def connect (receiver)
def disconnect (receiver)
def emit (*args)

 

  詳細描述
  Signal類提供了使用符合python語法習慣的方法來定義以及連接Qt信號。

  PySide改造了PyQt的新的信號與槽方法,除了下面提到的特別情況,PySide的實現可以與PyQt 4.5實現功能兼容。

  使用QtCore.Signal()定義新信號
  PySide自動為Qt內置的信號定義了信號。使用QtCore.Signal()工廠方法定義新的信號為類的屬性。

  QtCore.Signal()接受若干與信號簽名相關的參數類型。每個類型可以是Python類型對象或者C++類型的字符串名稱。同時,每個參數可以是類型參數的序列。本例中,每個序列定義了不同信號重載的簽名。第一個重載被設置為默認。

  也可以選擇性地提供一個參數 name 給QtCore.Signal(),其值可以設置信號的名稱。信號發射時,將使用類屬性的名字。

  下面,顯示一系列定義信號的方法:

 
from PySide import QtCore

class Foo(QtCore.QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = QtCore.pyqtSignal()

def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)

# Emit the signal.
self.trigger.emit()

def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"

  新信號只應該在QObject子類中定義。

  使用這個方法定義的新信號將會自動添加入類的QMetaObject中。這意味著,它們將在Qt Designer中出現,而且也可以使用QMetaObject API反射獲取。

  連接、斷開以及發射信號
  信號與槽之間可以用Signal.connect()和Signal.disconnect()方法進行連接和斷開,或者使用Signal.emit()方法發射信號。

  下面的代碼演示如何定義、連接以及發射沒有參數的信號

 
from PySide import QtCore

class Foo(QtCore.QObject):
# Define a new signal called 'trigger' that has no arguments.
trigger = QtCore.pyqtSignal()

def connect_and_emit_trigger(self):
# Connect the trigger signal to a slot.
self.trigger.connect(self.handle_trigger)

# Emit the signal.
self.trigger.emit()

def handle_trigger(self):
# Show that the slot has been called.
print "trigger signal received"

  下面則演示連接重載的信號

 
from PySide import QtGui

class Bar(QtGui.QComboBox):

def connect_activated(self):
# The PyQt documentation will define what the default overload is.
# In this case it is the overload with the single integer argument.
self.activated.connect(self.handle_int)

# For non-default overloads we have to specify which we want to
# connect. In this case the one with the single string argument.
# (Note that we could also explicitly specify the default if we
# wanted to.)
self.activated[str].connect(self.handle_string)

def handle_int(self, index):
print "activated signal passed integer", index

def handle_string(self, text):
print "activated signal passed string", text

  使用關鍵字參數連接信號
       在創建對象并想連接信號的時候,把槽作為關鍵字參數的值傳遞給構造函數。下面的代碼實際上是等價的。

 
act = QtGui.QAction("Action", self)
act.triggered.connect(self.on_triggered)

act
= QtGui.QAction("Action", self, triggered=self.on_triggered)

  Signal.connect(receiver[, type=Qt.AutoConnection])
  在singal和receiver之間創立連接,receiver可以是Python函數,或者槽或信號。
  Signal.disconnect(receiver)
  斷開singal與receiver間的連接。receiver同上。
  Signal.emit(*args)
  args是可選的參數序列,傳遞給任何已連接的槽。

0
0
 
標簽:PySide
 
 

文章列表

arrow
arrow
    全站熱搜
    創作者介紹
    創作者 大師兄 的頭像
    大師兄

    IT工程師數位筆記本

    大師兄 發表在 痞客邦 留言(0) 人氣()