Which QLabel was pressed by mousePressEvent

寵の児 提交于 2020-08-19 09:08:39

问题


How can I get in method on_product_clicked where QLabel is a mousePressEvent?

In the current example I see three images in the form. When I click the second image I need to have number 2 in the on_product_clicked method.

    product_images = ['first_icon.png', 'second_icon.png', 'third_icon.png']

    self.vbox_choice_img = QHBoxLayout()
    for image in product_images:
        label = QLabel()
        pixmap = QtGui.QPixmap(image)
        pixmap = pixmap.scaled(250, 250)
        label.setPixmap(pixmap)
        label.setAlignment(QtCore.Qt.AlignHCenter)
        label.mousePressEvent = self.on_product_clicked
        self.vbox_choice_img.addWidget(label)


def on_product_clicked(self, event, <WHICH_QLABEL_WAS_CLICKED>):
    pass

I used "self" in the example because it is a code from class.


回答1:


Assigning the mousePressEvent method to another function is not correct, mousePressEvent is not a signal, it is a function that is part of QLabel, so with your code you are disabling your normal task and you could generate many problems.

A possible solution is that you create a personalized QLabel that emits a signal created as shown below:

class ClickLabel(QtGui.QLabel):
    clicked = QtCore.pyqtSignal()

    def mousePressEvent(self, event):
        self.clicked.emit()
        QtGui.QLabel.mousePressEvent(self, event)
    product_images = ['first_icon.png', 'second_icon.png', 'third_icon.png']

    self.vbox_choice_img = QHBoxLayout()
    for image in product_images:
        label = ClickLabel()
        pixmap = QtGui.QPixmap(image)
        pixmap = pixmap.scaled(250, 250)
        label.setPixmap(pixmap)
        label.setAlignment(QtCore.Qt.AlignHCenter)
        label.clicked.connect(self.on_product_clicked)
        self.vbox_choice_img.addWidget(label)

def on_product_clicked(self):
    label = self.sender()


来源:https://stackoverflow.com/questions/50955182/which-qlabel-was-pressed-by-mousepressevent

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!