我想创建自己的树模型,结果是这样的:
如何使根元素显示出来?
class TreeItem
{
public:
explicit TreeItem(const QString &data, TreeItem* parent = 0);
~TreeItem();
void appendChild(TreeItem *child);
void setParent(TreeItem *parent);
TreeItem *child(int row);
int childCount() const;
QString data() const;
int row() const;
TreeItem *parentItem();
private:
QList<TreeItem*> _childItems;
QString _data;
TreeItem* _parentItem;
};
class TreeModel : public QAbstractItemModel
{
public:
explicit TreeModel( const QString &data, QObject *parent = 0 );
~TreeModel();
QVariant data( const QModelIndex &index, int role ) const override;
QVariant headerData(int section, Qt::Orientation orientation, int role) const;
Qt::ItemFlags flags( const QModelIndex &index ) const override;
QModelIndex index( int row, int column, const QModelIndex &parent = QModelIndex() ) const override;
QModelIndex parent( const QModelIndex &index) const override;
int rowCount( const QModelIndex &parent = QModelIndex() ) const override;
int columnCount( const QModelIndex &parent = QModelIndex() ) const override;
private:
TreeItem* _rootItem;
};
QModelIndex TreeModel::index(int row, int column, const QModelIndex &parent ) const
{
qDebug() << "TreeModel::index";
if ( !hasIndex(row, column, parent) )
return QModelIndex();
TreeItem* parentItem;
if ( !parent.isValid() )
parentItem = _rootItem;
else
parentItem = static_cast<TreeItem*>( parent.internalPointer() );
TreeItem* childItem = parentItem->child(row);
if (childItem)
return createIndex(row, column, childItem);
else
return QModelIndex();
}
QModelIndex TreeModel::parent(const QModelIndex &index) const
{
qDebug() << "TreeModel::parent";
if (!index.isValid())
return QModelIndex();
TreeItem *childItem = static_cast<TreeItem*>(index.internalPointer());
TreeItem *parentItem = childItem->parentItem();
if (parentItem == _rootItem)
return QModelIndex();
return createIndex(parentItem->row(), 0, parentItem);
}
MainWindow::MainWindow()
{
mainWindow.setupUi(this);
TreeModel* model = new TreeModel("abc");
mainWindow.treeView->setModel(model);
}
树的根元素的函数被称为invisibleRootItem并不是没有意义的。
向您的模型再添加一层,仅从第二层开始分支,然后一个根将在显示的部分中可见。