Search code examples
pythonimagepyqt5qcheckbox

PyQt5 QCheckbox with image


Is there a way to implement checkbox with image? I want to create side bar with the list of checkbox with images, like i did it here with html, css and js:

list of checkbox

The style is not important, first of all I want to know how to make the functionality. Thanks in advance!

Update #2

import sys
from PyQt5 import QtWidgets
from PyQt5.QtWidgets import *
from PyQt5.QtGui import *

app = QtWidgets.QApplication(sys.argv)
window = QtWidgets.QWidget()

layout = QVBoxLayout()

frame = QtWidgets.QFrame()
frame.setFrameShape(QFrame.StyledPanel)
frame.setLayout(layout)
layout.addWidget(frame)

cb = QCheckBox('Yes', frame)
layout.addWidget(cb)

lb = QLabel("Do you like programming?", cb)
lb.setPixmap(QPixmap("26.png"))
layout.addWidget(lb)

window.setLayout(layout)
window.show()
app.exec()

Solution

  • After all came to this solution:

    from PyQt5.QtWidgets import *
    from PyQt5.QtCore import *
    import sys
    from PyQt5 import QtGui, QtCore, QtWidgets
    import os
    icon_path = os.getcwd() + r"\26.png"
    
    class QDMQListWidget(QListWidget):
        def __init__(self):
            super().__init__()
    
        def mousePressEvent(self, event):
            super().mousePressEvent(event)
            if self.currentItem().checkState() == Qt.Checked:
                self.currentItem().setCheckState(Qt.Unchecked)
            elif self.currentItem().checkState() == Qt.Unchecked:
                self.currentItem().setCheckState(Qt.Checked)
    
    
    if __name__ == '__main__':
        app = QApplication(sys.argv)
        lw = QDMQListWidget()
        for i in range(5):
            text = f'{i}'
            icon = QtGui.QIcon(icon_path)
            item = QListWidgetItem(icon, text)
            item.setCheckState(Qt.Unchecked)
            lw.addItem(item)
        lw.setDragDropMode(lw.InternalMove)
        lw.setIconSize(QSize(400, 400))
        lw.setSelectionMode(True)
        lw.show()
        sys.exit(app.exec_())