blaz
blaz

Reputation: 4258

PySide: Connecting QComboBox indices with strings

I would like to connect the QComboBox indeces with specific strings (i.e. when I select "A", I want that it prints "A has been selected", and when I select "B", then "B has been selected").

I am new to PySide and learning, so I am sure there exists a simple solution. Help is appreciated.

from PySide import QtGui


class Widget(QtGui.QWidget):

    def __init__(self, parent=None):
        super().__init__(parent)

        v_global_layout = QtGui.QVBoxLayout()

        method_selection = QtGui.QComboBox()
        method_selection.addItem("A")
        method_selection.addItem("B")

        v_global_layout.addWidget(method_selection)
        self.setLayout(v_global_layout)

        def do_somethinh():
            print("A has been selected!!!")
        method_selection.activated.connect(do_somethinh)


if __name__ == '__main__':
    import sys
    app = QtGui.QApplication(sys.argv)

    main_window = Widget()
    main_window.setGeometry(100, 100, 640, 480)
    main_window.show()

    sys.exit(app.exec_())

Upvotes: 1

Views: 156

Answers (1)

ekhumoro
ekhumoro

Reputation: 120778

The QComboBox.activated signal has two overloads: one which sends the index of the chosen item, and one which sends its text. The default overload sends the index. To select the other overload, you need slightly different syntax:

    def do_somethinh(text):
        print(text, "has been selected!!!")
    method_selection.activated[str].connect(do_somethinh)

So signal objects have __getitem__ support, which lets you select a specific overload of a signal by passing the argument type as a key (if there's more than one argument, you can pass a tuple of types).

Upvotes: 1

Related Questions