QT学习笔记之QTreeWidget的增与删

写在前面

在实际的应用中,树形结构还是用的比较多的,比如安装目录的选择、查看部门的结构等等。所以学好属性结构还是大有裨益的。

增与删

下面是添加的功能:

//这是添加根节点的功能实现
this->connect(ui->Root_btn, SIGNAL(clicked(bool)), this, SLOT(addRoot()));

void Widget::addRoot()
{
    QString one = ui->first->text();
    QString two = ui->second->text();
    QString three = ui->third->text();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, one);
    item->setText(1, two);
    item->setText(2, three);
    ui->Tree->addTopLevelItem(item);
}

//这是添加叶子节点的实现
this->connect(ui->Child_btn, SIGNAL(clicked(bool)), this, SLOT(addChild()));

void Widget::addChild()
{
    QString one = ui->first->text();
    QString two = ui->second->text();
    QString three = ui->third->text();
    QTreeWidgetItem* parent = ui->Tree->currentItem();
    QTreeWidgetItem* item = new QTreeWidgetItem();
    item->setText(0, one);
    item->setText(1, two);
    item->setText(2, three);
    parent->addChild(item);
}

添加叶子节点字需要注意父节点的获取就可以了。

下面是删除节点的功能:

this->connect(ui->DEL_btn, SIGNAL(clicked(bool)), this, SLOT(deleteNode()));

void del(QTreeWidgetItem* node)
{
    if(node->childCount() > 0)
    {
        for(int i = 0; i < node->childCount(); i ++)
        {
            del(node->child(i));
        }
    }
    else
    {
        delete node;
    }
}

void Widget::deleteNode()
{
    QTreeWidgetItem* item = ui->Tree->currentItem();
    if(item->childCount() > 0)
    {
        for(int i = 0; i < item->childCount(); i ++)
        {
            del(item->child(i));
        }
    }
    delete item;
}

删除节点时记得循环删除这个节点下面的所有的子节点。

源码上传:http://download.csdn.net/detail/pkgk2013/9841470

posted @ 2017-05-13 13:51  $逝水无痕$  阅读(3450)  评论(0编辑  收藏  举报