Migui Mag
Migui Mag

Reputation: 187

How to remove a Qlabel in PyQt5

I have already read some answers but they do not work for me.

This is my code:

from PyQt5.QtWidgets import QWidget, QCheckBox, QApplication, QHBoxLayout, QLabel
from PyQt5.QtCore import Qt
from PyQt5.QtGui import QPixmap
import sys

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):     
        cbAll = QCheckBox('Slice 1', self)              # Slice 1 
        cbAll.move(1200, 130)
        cbAll.toggle()
        cbAll.stateChanged.connect(self.OpenSlice1)

        self.setGeometry(0, 25, 1365, 700)
        self.setWindowTitle('Original Slices')
        self.show()


    def OpenSlice1(self,state):
        pixmap = QPixmap("E:\BEATSON_PROJECT\python\GUI\home.png") 
        self.lbl = QLabel(self)          #Qlabel used to display QPixmap
        self.lbl.setPixmap(pixmap)
        if state == Qt.Checked:
            self.lbl.show()
        else:
            self.lbl.hide()

if __name__ == '__main__':

    app = QApplication(sys.argv)
    ex = Example()
    sys.exit(app.exec_())

However when it goes into the unchecked option it does not hide the image:

Original window: enter image description here

Checked Slice 1 window: enter image description here

From this point on it always shows the image and I want it to hide it. i.e unckecking the box does not work: enter image description here

Upvotes: 1

Views: 6978

Answers (1)

eyllanesc
eyllanesc

Reputation: 243993

The problem is caused because each time you press you are creating a new QLabel and you assign the same variable so you lose access to that element, and then you are closing the new QLabel, but not the old one. What you must do is create it and only hide it for it you could use the setVisible() or hide() and show() method.

class Example(QWidget):
    def __init__(self):
        super().__init__()
        self.initUI()

    def initUI(self):     
        cbAll = QCheckBox('Slice 1', self)              # Slice 1 
        cbAll.move(1200, 130)
        cbAll.toggle()
        cbAll.stateChanged.connect(self.OpenSlice1)
        pixmap = QPixmap("E:\BEATSON_PROJECT\python\GUI\home.png") 
        self.lbl = QLabel(self)          #Qlabel used to display QPixmap
        self.lbl.setPixmap(pixmap)
        self.setGeometry(0, 25, 1365, 700)
        self.setWindowTitle('Original Slices')
        self.show()

    def OpenSlice1(self, state):
        self.lbl.setVisible(state != Qt.Unchecked)
        # or
        """if state == Qt.Checked:
            self.lbl.show()
        else:
            self.lbl.hide()"""

Upvotes: 2

Related Questions