Domanda

I have a class that creates a window and a treeview. The code that creates the treeview is pretty simple and is in the init method:

    tableView = QTableView()
    tableView.setModel(model)
    tableView.clicked.connect(self.foo)  

Where 'foo' is the name of the function (a member of the same class) that should accept the callback. The function's signature is as follows:

def foo(something):
    print something  

From what (admittedly little) I understand, the 'something' parameter should've been an instance of QModelIndex, but it isn't. Doing a print(something) on the variable indicated that I've sent foo(...) the window class. What am I missing here? I assumed this was the right way to do this, based on:

http://qt-project.org/wiki/Signals_and_Slots_in_PySide

Any ideas?
Thank you for your help.

È stato utile?

Soluzione

First argument to a method is the instance itself which is passed implicitly and generally named as self. In your version, something becomes the instance, not the passed parameter. Your method should look like:

def foo(self, something):
    print something

As a side note, normally you would get an error while passing a parameter to a method that doesn't accept any. Like:

class Foo(object):
    def bar(something):
        print something

f = Foo()
f.bar(1)

#Traceback (most recent call last):
#  File "<stdin>", line 1, in <module>
#TypeError: bar() takes exactly 1 argument (2 given)

But in Qt, you can connect a signal to a slot that accepts less parameters. Qt will call the slot without that parameter. So, although the clicked signal passes the QModelIndex, you can still connect this signal to a method that doesn't accept a parameter (like your foo). In result, you'll get this silent 'bug'.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top