MainWindow::MainWindow(QWidget *parent)
: QMainWindow(parent)
, ui(new Ui::MainWindow)
{
ui->setupUi(this);
setWindowTitle("QTreeView的简单使用");
model = new QStandardItemModel;
model->setHorizontalHeaderLabels(QStringList() << "left" << "right");
ui->treeView->setModel(model);
ui->treeView->header()->setSectionResizeMode(QHeaderView::Stretch);
ui->treeView->header()->setDefaultAlignment(Qt::AlignHCenter);
connect(ui->treeView, &QTreeView::clicked, this, &MainWindow::clicked);
}
MainWindow::~MainWindow()
{
delete ui;
}
void MainWindow::on_pushButton_clicked()
{
int index = model->rowCount();
QList<QStandardItem *> topList;
//链表容器添加顶级节点
topList << new QStandardItem(QString("顶级节点:%1-left").arg(index + 1))
<< new QStandardItem(QString("顶级节点:%1-right").arg(index + 1));
topList[0]->setData(-1, Qt::UserRole + 1); //设置父节点行,当值为-1时则当前为顶级节点
topList[1]->setData(-1, Qt::UserRole + 1);
//添加顶级节点
model->appendRow(topList);
}
void MainWindow::on_pushButton_2_clicked()
{
//获取当前行列
QModelIndex curIndex = ui->treeView->currentIndex();
int row = curIndex.row();
int column = curIndex.column();
int parentRow = curIndex.data(Qt::UserRole + 1).toInt();
//当前行列值包含-1值或当前节点非顶级节点时返回
if( -1 == row || -1 == column)
{
return;
}
QStandardItem *item = model->itemFromIndex(curIndex);
QList<QStandardItem *> childList;
childList << new QStandardItem(QString("子节点:%1-left").arg(item->rowCount()))
<< new QStandardItem(QString("子节点:%1-right").arg(item->rowCount()));
//设置item的data
childList[0]->setData(row, Qt::UserRole + 1);
childList[1]->setData(row, Qt::UserRole + 1);
//添加子节点
item->appendRow(childList);
}
void MainWindow::on_pushButton_3_clicked()
{
//获取当前行列
QModelIndex curIndex = ui->treeView->currentIndex();
int row = curIndex.row();
int column = curIndex.column();
//当前行列值包含-1值或当前节点非顶级节点时返回
if( -1 == row || -1 == column)
{
return;
}
QStandardItem *item = model->itemFromIndex(curIndex);
if(item)
{
QStandardItem *parentItem = item->parent();
if(parentItem)
parentItem->removeRow(row);
else
model->removeRow(row);
}
}
void MainWindow::clicked()
{
//获取当前行列
QModelIndex curIndex = ui->treeView->currentIndex();
int row = curIndex.row();
int column = curIndex.column();
//当前位置包含-1值返回
if( -1 == row || -1 == column)
{
return;
}
ui->statusbar->showMessage(curIndex.data().toString());
}
DEMO下载:点击跳转
运行效果如下:
觉得有帮助的话,打赏一下呗。。