📜  PyQt5 – 复选框中的图像(1)

📅  最后修改于: 2023-12-03 15:18:50.015000             🧑  作者: Mango

PyQt5 – 复选框中的图像

在PyQt5中,我们可以在复选框中添加一个图像。这样可以使复选框看起来更加美观,也可以方便用户快速识别每个选项。

下面我们将通过一个例子来演示如何在复选框中添加图像。

首先,我们需要从QtWidgets库中导入QCheckBox类。然后,我们可以使用setStyleSheet方法来设置样式表,从而添加图像。我们还需要使用QPixmap类加载图像文件,并将其设置为复选框的图像。

代码如下:

import sys
from PyQt5.QtWidgets import QApplication, QWidget, QCheckBox
from PyQt5.QtGui import QPixmap

class App(QWidget):

    def __init__(self):
        super().__init__()
        self.title = 'PyQt5 checkbox - pythonspot.com'
        self.left = 10
        self.top = 10
        self.width = 320
        self.height = 200
        self.initUI()

    def initUI(self):
        checkbox = QCheckBox('Show title', self)
        checkbox.move(20, 20)
        checkbox.toggle()
        checkbox.stateChanged.connect(self.changeTitle)

        self.setWindowTitle(self.title)
        self.setGeometry(self.left, self.top, self.width, self.height)
        self.show()

    def changeTitle(self, state):
        if state ==  Qt.Checked:
            pixmap = QPixmap('pythonspot.png')
            self.setWindowIcon(pixmap)

        else:
            self.setWindowTitle(self.title)

if __name__ == '__main__':
    app = QApplication(sys.argv)
    ex = App()
    sys.exit(app.exec_())

在上述代码中,我们创建了一个名为“ Show title”的复选框。我们使用了stateChanged信号来检测复选框的状态,并根据需要更改窗口标题和图标。

我们使用QPixmap类从文件中加载pythonspot.png图像文件,并使用setWindowIcon方法将其设置为窗口图标。

在代码运行时,复选框初始处于选中状态。如果复选框被选中,则窗口标题将更改为“ Show title”,并将pythonspot.png设置为窗口图标。如果复选框未选中,则窗口标题将恢复为原始值。

这就是在PyQt5中添加图像到复选框中的方法。尝试使用上述示例代码添加自己的图像并更改与复选框相应的详细信息。