PyQt5可检查组合框:显示已检查项目列表

问题描述 投票:0回答:1

基于https://stackoverflow.com/a/22775990/7894940可检查组合框的实现,我想更进一步,并且能够直接在主QComboBox标签上显示已检查项目的列表,即当QComboBox的显示文本为不是“展开”。

到目前为止,我能够打印已检查项目的列表,但是我不知道如何使用前者来更改主要的QComboBox标签文本:

from PyQt5.QtWidgets import QApplication, QComboBox, QMainWindow, QWidget, QVBoxLayout
from PyQt5.QtGui import QStandardItemModel
from PyQt5.QtCore import Qt
import sys


class CheckableComboBox(QComboBox):
    def __init__(self):
        super(CheckableComboBox, 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)
        if item.checkState() == Qt.Checked:
            item.setCheckState(Qt.Unchecked)
            # print(item.text() + " was unselected.")
        else:
            item.setCheckState(Qt.Checked)
            # print(item.text() + " was selected.")
        self.check_items()

    def item_checked(self, index):
        item = self.model().item(index, 0)
        return item.checkState() == Qt.Checked

    def check_items(self):
        checkedItems = []
        for i in range(self.count()):
            if self.item_checked(i):
                checkedItems.append(self.model().item(i, 0).text())
        print(checkedItems)


class Dialog_01(QMainWindow):
    def __init__(self):
        super(QMainWindow, self).__init__()
        myQWidget = QWidget()
        myBoxLayout = QVBoxLayout()
        myQWidget.setLayout(myBoxLayout)
        self.setCentralWidget(myQWidget)
        self.ComboBox = CheckableComboBox()
        for i in range(3):
            self.ComboBox.addItem("Combobox Item " + str(i))
            item = self.ComboBox.model().item(i, 0)
            item.setCheckState(Qt.Unchecked)
        myBoxLayout.addWidget(self.ComboBox)

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

一张说明我想要的图片:Diagram

python pyqt pyqt5 qcombobox
1个回答
0
投票

您可以覆盖paintEvent方法:

© www.soinside.com 2019 - 2024. All rights reserved.