2012-08-10 144 views
5

在pyside中使用QComboBox,我知道如何連接信號並使用它發送的索引。但是unicode的說法呢?如果我更願意連接到需要組合框中的字符串的東西,那有可能嗎?重載的pyside信號(QComboBox)

來源: http://www.pyside.org/docs/pyside/PySide/QtGui/QComboBox.html#PySide.QtGui.QComboBox

兩個版本,一個帶有PySide.QtCore.QString參數,一個與int參數存在的所有三個信號。

信號

def activated (arg__1) 
def activated (index) 

PySide.QtGui.QComboBox.activated(指數) 參數:index - PySide.QtCore.int

PySide.QtGui.QComboBox.activated(arg_ 1) 參數:arg _1 - unicode

編輯:一些代碼。

le = ComboBoxIpPrefix() 
le.currentIndexChanged.connect(lambda x....) 

此代碼給了我索引。問題是如何獲得文檔中提到的unicode字符串。

回答

12

我不明白你的問題到底是什麼。

QComboBox.activated信號有兩個版本。 One爲您提供所選項目的索引,other one爲您提供文本。

要PySide二者之間做出選擇,你執行以下操作:

a_combo_box.activated[int].connect(some_callable) 

a_combo_box.activated[str].connect(other_callable) 

第二行可能不會在Python 2以這種方式工作,所以替代strunicode

請注意,我用的一般(C++)Qt文檔,因爲PySide文檔還是相當ambigous:我一直在到處看到這些arg__1小號...
「翻譯」到Python應該不會太難。請記住QString變成str(或Python2中的unicode;順便說一下,我喜歡讓我的代碼在Python的所有版本上都能正常工作,所以我通常在Py2中創建一個別名類型text,即str,即str);在Py2中,unicode; longshort等變爲int; double變成float;完全避免了QVariant,這只是意味着任何數據類型都可以在那裏傳遞;等等......

2

謝謝Oleh Prypin!當我在PySide文檔中遇到晦澀難懂的arg__1時,你的答案對我有幫助。

當我同時測試combo.currentIndexChanged [str]和combo.currentIndexChanged [unicode]時,每個信號都發送當前索引文本的unicode版本。

下面是演示行爲的一個例子:

from PySide import QtCore 
from PySide import QtGui 

class myDialog(QtGui.QWidget): 
    def __init__(self, *args, **kwargs): 
     super(myDialog, self).__init__(*args, **kwargs) 

     combo = QtGui.QComboBox() 
     combo.addItem('Dog', 'Dog') 
     combo.addItem('Cat', 'Cat') 

     layout = QtGui.QVBoxLayout() 
     layout.addWidget(combo) 

     self.setLayout(layout) 

     combo.currentIndexChanged[int].connect(self.intChanged) 
     combo.currentIndexChanged[str].connect(self.strChanged) 
     combo.currentIndexChanged[unicode].connect(self.unicodeChanged) 

     combo.setCurrentIndex(1) 

    def intChanged(self, index): 
     print "Combo Index: " 
     print index 
     print type(index) 

    def strChanged(self, value): 
     print "Combo String:" 
     print type(value) 
     print value 

    def unicodeChanged(self, value): 
     print "Combo Unicode String:" 
     print type(value) 
     print value 

if __name__ == "__main__": 

    app = QtGui.QApplication([]) 
    dialog = myDialog() 
    dialog.show() 
    app.exec_() 

輸出的結果是:

Combo Index 
1 
<type 'int'> 
Combo String 
<type 'unicode'> 
Cat 
Combo Unicode String 
<type 'unicode'> 
Cat 

我也證實,即basestring將拋出一個錯誤IndexError: Signature currentIndexChanged(PyObject) not found for signal: currentIndexChanged。 PySide出現分化intfloat(它指的是作爲double),str/unicode(兩者成爲unicode),和bool,但所有其他Python類型被解析爲PyObject對於信號特徵的目的。

希望能幫助別人!