Skip to content
Advertisement

Click a button and change MainWindow

I am learning Qt and I am interesting in how to change some features of MainWindow.

I was trying this code, but there were some errors when I clicked the first button:

JavaScript

what I did wrong (how could I do ‘the_second_button_was_clicked’ callable )?

main.py

JavaScript

clickedButton.py

JavaScript

Advertisement

Answer

The issue has nothing to do with PyQt, but with how classes and instances work.

The first argument of instance methods always refers to the instance of the class, and it’s called self just for convention: it could actually be named in any way as long as its syntax is valid, just like any other variable.

When using functions that are declared outside a class, it’s good practice to avoid that naming convention (mostly to avoid confusion when reading code).

What is happening is that the self in def the_first_button_was_clicked(self): refers to the instance of MainWindow, which has no the_second_button_was_clicked method, hence the AttributeError exception.

The point is that both your functions are just functions, not methods (which are functions of an instance or a class): they are not members of the class.

Also note that creating a direct connection to the function will not work, as the self argument is only “created” when a function is a method.
As Heike pointed out in the comments, a possibility is to use lambda, which allows keeping an actual reference to the instance, while directly calling the function, which will be executed using the self argument provided, exactly as you did in run_the_first_button_was_clicked.

In the following examples I’m replacing self with mainWinInstance in order to make things more clear (which is the reason for which self should not be used in these cases).

JavaScript

Another possibility is to make the second function a member of the instance:

JavaScript

or:

JavaScript

In both cases the instance attribute has to be created before the connection (which also means before calling the first function in the first case).

Consider that this “monkey patching” approaches should only be used in special cases (mostly due to objects that cannot be subclassed because created autonomously), especially if done outside the class or even the script.

In most cases, what you’re doing is considered bad practice, and if you’re doing this with a class created on your own, there’s probably something really wrong in your implementation: you should better rethink your logic and implement everything within the class itself.

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement