我已经尝试了几天来弄清楚为什么我的QAbstractLisModel不允许用户在三种状态下切换可检查项目。模型在flags()方法中返回Qt.IsTristate
和Qt.ItemIsUserCheckable
,但是当程序运行时,只有Qt.Checked和Qt.Unchecked在编辑时切换。
class cboxModel(QtCore.QAbstractListModel):
def __init__(self, parent=None):
super(cboxModel, self).__init__(parent)
self.cboxes = [
['a',0],
['b',1],
['c',2],
['d',0]
]
def rowCount(self,index=QtCore.QModelIndex()):
return len(self.cboxes)
def data(self,index,role):
if not index.isValid: return QtCore.QVariant()
myname,mystate = self.cboxes[index.row()]
if role == QtCore.Qt.DisplayRole:
return QtCore.QVariant(myname)
if role == QtCore.Qt.CheckStateRole:
if mystate == 0:
return QtCore.QVariant(QtCore.Qt.Unchecked)
elif mystate == 1:
return QtCore.QVariant(QtCore.Qt.PartiallyChecked)
elif mystate == 2:
return QtCore.QVariant(QtCore.Qt.Checked)
return QtCore.QVariant()
def setData(self,index,value,role=QtCore.Qt.EditRole):
if index.isValid():
self.cboxes[index.row()][1] = value.toInt()[0]
self.emit(QtCore.SIGNAL("dataChanged(QModelIndex,QModelIndex)"),
index, index)
print self.cboxes
return True
return False
def flags(self,index):
if not index.isValid():
return QtCore.Qt.ItemIsEditable
return QtCore.Qt.ItemIsEnabled | QtCore.Qt.ItemIsEditable | QtCore.Qt.ItemIsUserCheckable | QtCore.Qt.ItemIsTristate
你可以用它来测试它,
class MainForm(QtGui.QMainWindow):
def __init__(self, parent=None):
super(MainForm, self).__init__(parent)
model = cboxModel(self)
self.view = QtGui.QListView()
self.view.setModel(model)
self.setCentralWidget(self.view)
app = QtGui.QApplication(sys.argv)
form = MainForm()
form.show()
app.exec_()
并且看到只有2个州可用。我假设有一些简单的我缺少。有任何想法吗?谢谢!
答案 0 :(得分:0)
您可能需要在clicked()信号上创建一个自定义插槽,该插槽循环显示三种状态。通常,三态元素仅能够直接点击和关闭,并且仅在子元素处于不同状态时才处于部分检查模式。
答案 1 :(得分:0)