控制MousePressEvent在PyQt中返回的对象

时间:2016-01-03 03:47:33

标签: python pyqt qimage qlabel qpushbutton

我有很多显示图片的qlabels。点击此qlabels mousePressEvent会返回点击的对象,然后我会在另一个qlabel的大尺寸中显示此图片。然后我可以使用qpushbutton删除图片。如果用户点击了更多qlabels然后单击qpushbutton,删除所有图像。我希望用户每次点击删除一个图像。所以我写了一个删除图像的方法,但是如果用户点击了很多图像并删除它们,我无法控制。我怎么能这样做?

labels[i].mousePressEvent = functools.partial(self.label_click, source_label = labels[i] ,source_image = pixmap)

def label_click(self, event,source_label=None, source_image=None):

        self.labelDisplayBigImage.setPixmap(source_image)
        self.labelDisplayBigImage.setScaledContents(True)

        if(source_label.picture() == self.labelDisplayBigImage.picture()):
            self.btnCancel.clicked.connect(source_label.clear)
            self.btnCancel.clicked.connect(self.labelDisplayBigImage.clear)

1 个答案:

答案 0 :(得分:1)

您可以使用QListWidget()selectionMode()的默认QListWidget是singleSelection。 将图像作为QIcon直接添加到listwidget并设置适当的iconSize:

class MyList(QtWidgets.QListWidget):
    def __init__(self):
        QtWidgets.QListWidget.__init__(self)
        images = ['IMG_1.jpeg', 'IMG_2.jpeg', 'IMG_3.jpeg', 'IMG_4.jpeg', 'IMG_5.jpeg']       
        for i in images:
            icon = QtGui.QIcon(i)
            item = QtWidgets.QListWidgetItem(icon, i)  
            self.addItem(item)
        self.setIconSize(QtCore.QSize(150,100))
        self.setSelectionMode(1)            # 1 = SingleSelection, 2 = MultiSelection, not necessary, default mode is singleSelection
        self.setGeometry(200,200,300,500)

或将包含图像的标签添加到listwidget,然后必须给出该项目的适当sizeHint:

        for i in images:
            label = QtWidgets.QLabel(self)
            pm = QtGui.QPixmap(i)
            label.setPixmap(pm.scaled(QtCore.QSize(150,100)))
            item = QtWidgets.QListWidgetItem(i)
            item.setSizeHint(QtCore.QSize(200,110))
            self.addItem(item)
            self.setItemWidget(item,label)

连接到currentItemChanged-signal以获取所选项目(洞穴:此信号发送2个项目,当前和之前的项目)

        self.currentItemChanged.connect(self.findSel)

    def findSel(self, current, previous):
        print(current.text())
        try:
            print(previous.text())
        except AttributeError:
            print('first selection, no previous item!')