如何在组合框中创建树视图(带复选框) - PyQt
我正在使用PYQT来开发一个应用程序。我需要在下拉框(combobox)里的选项中插入一个带复选框的树形视图。我想知道该怎么做?
我有以下代码,但这段代码没有效果。
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)
请告诉我是否漏掉了什么。
2 个回答
0
如果你真的想把一个布局应用到另一个布局上,试着把你的控件添加到你的 cb_layout 里面。否则,就把你的子布局去掉吧。
0
你应该创建一个模型,这个模型在数据和设置数据的方法中支持Qt.CheckStateRole,并且在标志方法中使用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)