我正在尝试使用简单的树模型,但我无法使该示例在我的项目中工作。
首先,我可以毫无问题地使用 QTreeView 和 QStandardItemModel。在以下情况下,我可以看到我的 QTreeView 里面有数据。查看工作代码:
constructor{
m_pModel = new QStandardItemModel();
ui.treeViewDevicesList->setModel(m_pModel);
fillTreeView(devicesList);
}
void GatewayDeviceViewerEditor::fillTreeView(const std::vector<Payload> &devicesList)
{
QVector<QStandardItem *> parents(MAX_PARENTS);
parents[0] = m_pModel->invisibleRootItem();
for (vector<Payload>::const_iterator it = devicesList.begin() ; it != devicesList.end(); ++it)
{
QStandardItem *pTreeViewItem = new QStandardItem();
string rootTitle = it->deviceId + " " + it->deviceName + " " + it->status ;
pTreeViewItem->setText(rootTitle.c_str());
parents[0]->appendRow(pTreeViewItem);
// parents[1] = pTreeViewItem;
}
}
现在,以下代码不起作用。我正在尝试对模型进行子类化。在这种情况下,QTreeView 显示出来但完全是空的。有一些我想我不明白的地方。
entryPoint{
DeviceTreeModel deviceTreeModel(devicesList);
ui.treeViewDevicesList->setModel(&deviceTreeModel);
}
DeviceTreeModel::DeviceTreeModel(const std::vector<Payload> &devicesList, QObject *parent)
: QAbstractItemModel(parent)
{
QList<QVariant> rootData;
rootData << "Title" << "Summary";
m_pRootItem = new DeviceTreeItem(rootData);
setupModelData(devicesList, m_pRootItem);
}
void DeviceTreeModel::setupModelData(const std::vector<Payload> &devicesList, DeviceTreeItem *parent)
{
QList<DeviceTreeItem*> parents;
parents << parent;
for (vector<Payload>::const_iterator it = devicesList.begin() ; it != devicesList.end(); ++it)
{
string rootTitle = it->deviceId + " " + it->deviceName + " " + it->status ;
QString test(rootTitle.c_str());
QList<QVariant> columnData;
columnData << test << "Summary";
parents.last()->appendChild(new DeviceTreeItem(columnData, parents.last()));
}
}