【问题标题】:How do I create a tree view (with checkbox) inside a combo box - PyQt如何在组合框中创建树视图(带复选框) - PyQt
【发布时间】:2011-07-10 08:22:12
【问题描述】:

我正在使用 PYQT 开发应用程序。我的要求是在组合框项目内插入带有复选框的树视图。我想知道如何实现这一目标?

我有以下代码,但这不起作用。

class CheckboxInsideListbox(QWidget):
def __init__(self, parent = None):
    super(CheckboxInsideListbox, self).__init__(parent)
    self.setGeometry(250,250,300,300)
    self.MainUI()

def MainUI(self):
    #stb_label = QLabel("Select STB\'s")
    stb_combobox = QComboBox()

    length = 10
    cb_layout = QVBoxLayout(stb_combobox)
    for i in range(length):
        c = QCheckBox("STB %i" % i)
        cb_layout.addWidget(c)

    main_layout = QVBoxLayout()
    main_layout.addWidget(stb_combobox)
    main_layout.addLayout(cb_layout)



    self.setLayout(main_layout)

如果我在这里遗漏了什么,请告诉我。

【问题讨论】:

    标签: python pyqt


    【解决方案1】:

    您应该创建一个模型,在 data 和 SetData 方法中支持 Qt.CheckStateRole,在 flags 方法中支持标志 Qt.ItemIsUserCheckable。

    我在这里粘贴一个我在项目中使用的示例,这是用于任何模型的 QSortFilterProxyModel 通用实现,但您可以在模型实现中使用相同的想法,显然我在您拥有的这个子类中使用内部结构不是直接在 PyQt 中,而是附加到我的内部实现(self.booleanSet 和 self.readOnlySet)。

    def flags(self, index):
        if not index.isValid():
            return Qt.ItemIsEnabled
    
        if index.column() in self.booleanSet:
            return Qt.ItemIsUserCheckable | Qt.ItemIsSelectable | Qt.ItemIsEnabled
        elif index.column() in self.readOnlySet:
            return Qt.ItemIsSelectable | Qt.ItemIsEnabled
        else:
            return QSortFilterProxyModel.flags(self, index)
    
    def data(self, index, role):
        if not index.isValid():
            return QVariant()
    
        if index.column() in self.booleanSet and role in (Qt.CheckStateRole, Qt.DisplayRole):
            if role == Qt.CheckStateRole:
                value = QVariant(Qt.Checked) if index.data(Qt.EditRole).toBool() else QVariant(Qt.Unchecked)
                return value
            else: #if role == Qt.DisplayRole:
                return QVariant()
        else:
            return QSortFilterProxyModel.data(self, index, role)
    
    def setData(self, index, data, role):
        if not index.isValid():
            return False
    
        if index.column() in self.booleanSet and role == Qt.CheckStateRole:
            value = QVariant(True) if data.toInt()[0] == Qt.Checked else QVariant(False)
            return QSortFilterProxyModel.setData(self, index, value, Qt.EditRole)
        else:
            return QSortFilterProxyModel.setData(self, index, data, role)
    

    【讨论】:

      【解决方案2】:

      如果您真的想将布局应用到布局,请尝试将小部件添加到 cb_layout。否则,请摆脱您的子布局。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2011-07-03
        • 1970-01-01
        • 1970-01-01
        • 2015-04-13
        • 1970-01-01
        • 2020-06-10
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多