mousePressEvent 按下了哪个 QLabel [英] Which QLabel was pressed by mousePressEvent

查看:83
本文介绍了mousePressEvent 按下了哪个 QLabel的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如何进入方法 on_product_clicked ,其中 QLabel 是一个 mousePressEvent?

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

在当前示例中,我在表单中看到了三个图像.当我点击第二张图片时,我需要在 on_product_clicked 方法中有数字 2.

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

我在示例中使用了self",因为它是来自类的代码.

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

推荐答案

将 mousePressEvent 方法分配给另一个函数是不正确的,mousePressEvent 不是信号,它是 QLabel 的一部分,因此您的代码是禁用您的正常任务,您可能会产生许多问题.

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.

一个可能的解决方案是创建一个个性化的QLabel,它发出如下所示的信号:

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()

这篇关于mousePressEvent 按下了哪个 QLabel的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆