超载的PySide信号(QComboBox)

6
使用pyside的QComboBox,我知道如何连接信号并使用它发送的索引。但是unicode参数怎么办?如果我更喜欢连接到想要来自组合框的字符串的东西,是否可能?

From: 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) 参数: index – PySide.QtCore.int

PySide.QtGui.QComboBox.activated(arg_1) 参数: arg_1 – unicode

编辑:一些代码。

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

这段代码给出了索引。问题是如何获取文档中提到的Unicode字符串。

2个回答

13
我不明白你的问题是什么。
QComboBox.activated信号有两个版本。其中一个给出所选项的索引,另一个给出所选项的文本。
在PySide中进行选择,可以按照以下步骤进行:
a_combo_box.activated[int].connect(some_callable)

a_combo_box.activated[str].connect(other_callable)

第二行在Python 2中可能无法正常工作,因此请用unicode替换str
请注意,我使用通用(C ++)Qt文档,因为PySide文档仍然相当模糊:我一直看到那些arg__1 ...转换成Python不应该太难。只需记住QString变为str(或Python 2中的unicode;顺便说一句,我喜欢我的代码在所有版本的Python上工作,所以我通常会创建一个别名类型text,在Py3中为str,在Py2中为unicode);longshort等变为intdouble变为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以用于信号签名的目的。
希望这能帮助到某些人!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接