python - 如何在 PyQt5 中删除 Qlabel

标签 python pyqt pyqt5 qlabel

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

这是我的代码:

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

选中切片 1 窗口: enter image description here

从现在开始,它总是显示图像,而我希望它隐藏它。即,打开盒子不起作用: 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()"""

关于python - 如何在 PyQt5 中删除 Qlabel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48586875/

相关文章:

python - 从 cython 写入文件

python-ldap 创建一个组

python - 从字符串中过滤字符

python - 无法在 Linux 上构建 PYQT

python - 如何从 Qtablewidget 中拖动图像并将其添加到场景中?

python - PyQt点击图像的不同部分有各自的功能

python - 拆分list的python列表

python - PyQt:监听 ip、端口时窗口停止响应

python - 'QPixmap' 没有属性 'grabWindow'

python - Qt 按钮样式从 ui 预览到原始窗口各不相同