PyQT Fusion样式删除了可检查组合框中的复选框

时间:2018-10-27 18:54:15

标签: python pyqt qcombobox qcheckbox qstyle

我使用以下代码创建了一个可检查的qcombobox。然后,我应用了融合样式以使程序看起来更好。但是,这样做将导致我的代码中的项目旁边的复选框不再可见。我该如何解决?

class WindowGUI(QMainWindow):
    def __init__(self, gui):
        super().__init__()
        self.initUI(gui)

    def initUI(self, gui):
        self.teacherSelect = TeacherSelect()

        self.setCentralWidget(self.teacherSelect)


class TeacherSelect(QComboBox):
    def __init__(self, parent):
        super().__init__(parent)
        self.parent = parent

        self.initModel()
        self.addTeachers()

    def initModel(self):
        self.number = 1
        self.selecteds = []
        self.teacherDataWids = []

        self.view().pressed.connect(self.select)

    def addTeachers(self):
        self.source = {"id1" : "a", "id2" : "b"}
        self.number = 0
        for teacherID in self.source.keys():
            self.addItem(self.source[teacherID])
            teacherItem = self.model().item(self.number)
            teacherItem.setData(teacherID)
            teacherItem.setCheckState(Qt.Unchecked)
            self.number += 1

    def select(self, index):
        pass

if __name__ == '__main__':

    app = QApplication(sys.argv)
    app.setStyle("fusion")

    windowGUI = WindowGUI()
    windowGUI.show()    

    sys.exit(app.exec_())

1 个答案:

答案 0 :(得分:0)

您必须在视图中建立一个委托,我也花了一些时间来改进您的代码:

from PyQt5 import QtCore, QtWidgets


class WindowGUI(QtWidgets.QMainWindow):
    def __init__(self, parent=None):
        super().__init__()
        self.initUI()

    def initUI(self):
        self.teacherSelect = TeacherSelect()
        self.setCentralWidget(self.teacherSelect)


class TeacherSelect(QtWidgets.QComboBox):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.initModel()
        self.addTeachers()
        # get parent with self.parent() or self.parentWidget()

    def initModel(self):
        self.number = 1
        self.selecteds = []
        self.teacherDataWids = []
        self.view().pressed.connect(self.select)
        delegate = QtWidgets.QStyledItemDelegate(self.view()) # <--
        self.view().setItemDelegate(delegate)                 # <--

    def addTeachers(self):
        source = {"id1" : "a", "id2" : "b"}

        for i, (k, v) in enumerate(source.items()):
            self.addItem(v)
            it = self.model().item(i)
            it.setData(k)
            it.setCheckable(True)
            it.setCheckState(QtCore.Qt.Unchecked)

    def select(self, index):
        pass

if __name__ == '__main__':
    import sys

    app = QtWidgets.QApplication(sys.argv)
    combo = WindowGUI()
    combo.resize(100, 40)
    combo.show()    

    sys.exit(app.exec_())