如何在PyQt5中删除Qlabel

问题描述 投票:1回答:1

我已经阅读了一些答案,但它们对我不起作用。

这是我的代码:

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

但是当它进入未选中的选项时,它不会隐藏图像:

原始窗口:enter image description here

Checked Slice 1窗口:enter image description here

从这一点开始,它总是显示图像,我希望它隐藏它。 o.r取消选中该框不起作用:qazxsw poi

python pyqt pyqt5 qlabel
1个回答
1
投票

问题是因为每次按下你都会创建一个新的enter image description here而你分配相同的变量,所以你失去了对该元素的访问权限,然后你关闭了新的QLabel,而不是旧的QLabel。你必须做的是创建它,只隐藏它,你可以使用setVisible()hide()show()方法。

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()"""
© www.soinside.com 2019 - 2024. All rights reserved.