我正在尝试使用simple tree model,但我无法让该示例在我的项目中有效。
首先,我能够使用QStandardItemModel毫无问题地使用QTreeView。在下面的例子中,我能够看到里面有数据的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()));
}
}
答案 0 :(得分:1)
在entryPoint
中,我认为deviceTreeModel
需要使用new
进行分配,而不是在退出函数时将被销毁的本地实例。