P
P
Philip Bondarev2017-08-28 07:50:35
Python
Philip Bondarev, 2017-08-28 07:50:35

How to determine which QLabel triggered mousePressEvent?

All good.
I am writing an interface in PyQt5. I have a QFrame that contains 9 QLabels with a QPixmap(QImage). When I click on the image (QLabel), I call the function.
At the moment, the problem is that I implemented everything very crookedly, not at all the 'pythonic way' (although I, as a self-taught person, usually don't worry about beauty, because I don't know what it is (I'm an old soldier, and I don't I know the words of love, Donna Rosa ...)). In __init__() of the main window, I write this crap:

self.ui.label_gv_0.mousePressEvent = self.set_img_0
    self.ui.label_gv_1.mousePressEvent = self.set_img_1
    self.ui.label_gv_2.mousePressEvent = self.set_img_2
    self.ui.label_gv_3.mousePressEvent = self.set_img_3
    self.ui.label_gv_4.mousePressEvent = self.set_img_4
    self.ui.label_gv_5.mousePressEvent = self.set_img_5
    self.ui.label_gv_6.mousePressEvent = self.set_img_6
    self.ui.label_gv_7.mousePressEvent = self.set_img_7
    self.ui.label_gv_main.mousePressEvent = self.set_img_m

Accordingly, you have to create 9 identical functions, which is a shame. Here is an example:
def set_img_0(self, event):
    global last_buffered_img
    last_buffered_img = nine['img_0']
    self.show_img(nine['img_0'])
    self.del_img()
    self.nine_in_one()

As I understand it, from QMouseEvent, you can only get information about coordinates, but not about a specific object. Tell me what to do in such situations? How to catch which specific image was clicked, or how to pass a parameter with the name of the image to the called method when catching an event like this? How in general in python to group such things so that it turns out beautifully, concisely and elegantly?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Andrei Smirnov, 2017-08-28
@Dogrtt

QSignalMapper will help you, just for this. An example is in the documentation.

D
devalone, 2017-08-28
@devalone

There is a static sender method to make sure it's a QLabel use qobject_cast:

auto label = qobject_cast<QLabel *>(sender());
if(!label)
  return;

This is C++ code if anything

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question