如何在PyQt5中删除Qlabel

米吉·马格(Migui Mag)

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

这是我的代码:

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

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

原始窗口: 在此处输入图片说明

Checked Slice 1窗口: 在此处输入图片说明

从这一点来看,它总是显示图像,我希望它隐藏它。即拆箱不起作用:在此处输入图片说明

永乐

造成该问题的原因是,每按一次,您将创建一个新QLabel变量,并且分配相同的变量,因此您将无法访问该元素,然后关闭新变量QLabel,而不是关闭变量您必须要做的就是创建它,并且仅对其隐藏即可,您可以使用setVisible()orhide()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()"""

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章