PyQt: How to set Combobox Items be Checkable?

To keep the GUI widgets number to minimum I need to find a way to give to user a choice of pull-down menu items that could be used to filter out the displayed in a listWidget items.
Let’s say the listWidget lists 5 different categories of Items: “Cat A”, “Cat B”,”Cat C”,”Cat D”,”Cat E”. I could implement the radio or checkboxes for each item category. But then 5 radio buttons or checkboxes would take a lot of GUI space. A combobox with the checkable items seems to be a right choice. Any ideas?

from PyQt4 import QtGui, QtCore
import sys, os


class CheckableComboBox(QtGui.QComboBox):
    def __init__(self):    
        super(CheckableComboBox, self).__init__()

    def flags(self, index):
        return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled


class Dialog_01(QtGui.QMainWindow):
    def __init__(self):
        super(QtGui.QMainWindow,self).__init__()

        myQWidget = QtGui.QWidget()
        myBoxLayout = QtGui.QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)

        self.ComboBox = CheckableComboBox()
        for i in range(3):
            self.ComboBox.addItem("Combobox Item " + str(i))

        myBoxLayout.addWidget(self.ComboBox)


if __name__ == '__main__':
    app = QtGui.QApplication(sys.argv)
    dialog_1 = Dialog_01()
    dialog_1.show()
    dialog_1.resize(480,320)
    sys.exit(app.exec_())

0

This idea of a multi-select combo has come up before, but I’m not sure that its the best solution. Really, all that’s needed is a tool-button with a drop-down menu (similar to the history buttons in a web-browser).

Here’s a basic demo that illustrates both options (button left, combo right):

PyQt5:

from PyQt5 import QtCore, QtGui, QtWidgets

class CheckableComboBox(QtWidgets.QComboBox):
    def __init__(self, title = '', parent=None):
        super().__init__(parent)
        self.setTitle(title)
        self.view().pressed.connect(self.handleItemPressed)
        self.setModel(QtGui.QStandardItemModel(self))

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)

    def title(self):
        return self._title

    def setTitle(self, title):
        self._title = title
        self.repaint()

    def paintEvent(self, event):
        painter = QtWidgets.QStylePainter(self)
        painter.setPen(self.palette().color(QtGui.QPalette.Text))
        opt = QtWidgets.QStyleOptionComboBox()
        self.initStyleOption(opt)
        opt.currentText = self._title
        painter.drawComplexControl(QtWidgets.QStyle.CC_ComboBox, opt)
        painter.drawControl(QtWidgets.QStyle.CE_ComboBoxLabel, opt)

class Dialog(QtWidgets.QWidget):
    def __init__(self):
        super().__init__()
        hbox = QtWidgets.QHBoxLayout()
        self.comboBox = CheckableComboBox('Categories', self)
        self.toolButton = QtWidgets.QToolButton(self)
        self.toolButton.setText('Categories ')
        self.toolMenu = QtWidgets.QMenu(self)
        for index in range(3):
            self.comboBox.addItem(f'Category {index}')
            item = self.comboBox.model().item(index, 0)
            item.setCheckState(QtCore.Qt.Unchecked)
            action = self.toolMenu.addAction(f'Category {index}')
            action.setCheckable(True)
        self.toolButton.setMenu(self.toolMenu)
        self.toolButton.setPopupMode(QtWidgets.QToolButton.InstantPopup)
        hbox.addWidget(self.toolButton)
        hbox.addWidget(self.comboBox)
        layout = QtWidgets.QVBoxLayout(self)
        layout.addLayout(hbox)
        layout.addStretch()

if __name__ == '__main__':

    app = QtWidgets.QApplication(['Test'])
    dialog = Dialog()
    dialog.show()
    app.exec()
        

PyQt4:

from PyQt4 import QtCore, QtGui

class CheckableComboBox(QtGui.QComboBox):
    def __init__(self, title = '', parent=None):
        super().__init__(parent)
        self.setTitle(title)
        self.view().pressed.connect(self.handleItemPressed)
        self.setModel(QtGui.QStandardItemModel(self))

    def handleItemPressed(self, index):
        item = self.model().itemFromIndex(index)
        if item.checkState() == QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Unchecked)
        else:
            item.setCheckState(QtCore.Qt.Checked)

    def title(self):
        return self._title

    def setTitle(self, title):
        self._title = title
        self.repaint()

    def paintEvent(self, event):
        painter = QtGui.QStylePainter(self)
        painter.setPen(self.palette().color(QtGui.QPalette.Text))
        opt = QtGui.QStyleOptionComboBox()
        self.initStyleOption(opt)
        opt.currentText = self._title
        painter.drawComplexControl(QtGui.QStyle.CC_ComboBox, opt)
        painter.drawControl(QtGui.QStyle.CE_ComboBoxLabel, opt)

class Dialog(QtGui.QWidget):
    def __init__(self):
        super().__init__()
        hbox = QtGui.QHBoxLayout()
        self.comboBox = CheckableComboBox('Categories', self)
        self.toolButton = QtGui.QToolButton(self)
        self.toolButton.setText('Categories ')
        self.toolMenu = QtGui.QMenu(self)
        for index in range(3):
            self.comboBox.addItem('Category %s' % index)
            item = self.comboBox.model().item(index, 0)
            item.setCheckState(QtCore.Qt.Unchecked)
            action = self.toolMenu.addAction('Category %s' % index)
            action.setCheckable(True)
        self.toolButton.setMenu(self.toolMenu)
        self.toolButton.setPopupMode(QtGui.QToolButton.InstantPopup)
        hbox.addWidget(self.toolButton)
        hbox.addWidget(self.comboBox)
        layout = QtGui.QVBoxLayout(self)
        layout.addLayout(hbox)
        layout.addStretch()

if __name__ == '__main__':

    app = QtGui.QApplication(['Test'])
    dialog = Dialog()
    dialog.show()
    app.exec()

7

It is very easy. Just set the item Checkable using the flags() function in the model associated with the comboBox.

def flags(self, index):
    return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled

UPDATE


This may not be the best method, But it should sort your problem. Here is a something u may want look at , IF you have space restrictionn and cannot display the complete listView, Just resize it until it looks like a ComboBox.

4

(Not an answere to the question, hence I used most of the code from here)

I added a function and changed the name to RadioComboBox if anyone else wants to have a class for a RadioComboBox.

from PyQt4 import QtCore
from PyQt4.QtGui import QComboBox, QStandardItemModel


class RadioComboBox(QComboBox):
    def __init__(self):
        super(RadioComboBox, self).__init__()
        self.view().pressed.connect(self.handle_item_pressed)
        self.setModel(QStandardItemModel(self))

    def handle_item_pressed(self, index):
        item = self.model().itemFromIndex(index)
        target_row = item.index().row()
        if item.checkState() != QtCore.Qt.Checked:
            item.setCheckState(QtCore.Qt.Checked)
        self.check_others(target_row)

    def check_others(self, target_row):
        for i in range(self.model().rowCount()):
            if i == target_row:
                continue
            else:
                item = self.model().item(i)
                item.setCheckState(QtCore.Qt.Unchecked)

Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa Dịch vụ tổ chức sự kiện 5 sao Thông tin về chúng tôi Dịch vụ sinh nhật bé trai Dịch vụ sinh nhật bé gái Sự kiện trọn gói Các tiết mục giải trí Dịch vụ bổ trợ Tiệc cưới sang trọng Dịch vụ khai trương Tư vấn tổ chức sự kiện Hình ảnh sự kiện Cập nhật tin tức Liên hệ ngay Thuê chú hề chuyên nghiệp Tiệc tất niên cho công ty Trang trí tiệc cuối năm Tiệc tất niên độc đáo Sinh nhật bé Hải Đăng Sinh nhật đáng yêu bé Khánh Vân Sinh nhật sang trọng Bích Ngân Tiệc sinh nhật bé Thanh Trang Dịch vụ ông già Noel Xiếc thú vui nhộn Biểu diễn xiếc quay đĩa Dịch vụ tổ chức tiệc uy tín Khám phá dịch vụ của chúng tôi Tiệc sinh nhật cho bé trai Trang trí tiệc cho bé gái Gói sự kiện chuyên nghiệp Chương trình giải trí hấp dẫn Dịch vụ hỗ trợ sự kiện Trang trí tiệc cưới đẹp Khởi đầu thành công với khai trương Chuyên gia tư vấn sự kiện Xem ảnh các sự kiện đẹp Tin mới về sự kiện Kết nối với đội ngũ chuyên gia Chú hề vui nhộn cho tiệc sinh nhật Ý tưởng tiệc cuối năm Tất niên độc đáo Trang trí tiệc hiện đại Tổ chức sinh nhật cho Hải Đăng Sinh nhật độc quyền Khánh Vân Phong cách tiệc Bích Ngân Trang trí tiệc bé Thanh Trang Thuê dịch vụ ông già Noel chuyên nghiệp Xem xiếc khỉ đặc sắc Xiếc quay đĩa thú vị
Trang chủ Giới thiệu Sinh nhật bé trai Sinh nhật bé gái Tổ chức sự kiện Biểu diễn giải trí Dịch vụ khác Trang trí tiệc cưới Tổ chức khai trương Tư vấn dịch vụ Thư viện ảnh Tin tức - sự kiện Liên hệ Chú hề sinh nhật Trang trí YEAR END PARTY công ty Trang trí tất niên cuối năm Trang trí tất niên xu hướng mới nhất Trang trí sinh nhật bé trai Hải Đăng Trang trí sinh nhật bé Khánh Vân Trang trí sinh nhật Bích Ngân Trang trí sinh nhật bé Thanh Trang Thuê ông già Noel phát quà Biểu diễn xiếc khỉ Xiếc quay đĩa
Thiết kế website Thiết kế website Thiết kế website Cách kháng tài khoản quảng cáo Mua bán Fanpage Facebook Dịch vụ SEO Tổ chức sinh nhật