微光

最孤独的时光会塑造最坚强的自己。

导航

Qt之QTreeWidget入门

Posted on 2019-04-09 18:25  我不是微光  阅读(19805)  评论(0编辑  收藏  举报

QTreeWidget的一些基本操作

1.insertTopLevelItems,insertTopLevelItem用来添加顶层的item

QTreeWidget *treeWidget = new QTreeWidget(this);//创建
treeWidget->setColumnCount(1);  //设置列
treeWidget->setHeaderLabel(tr("item tree"));    //设置标题
treeWidget->setGeometry(0,0,this->width(),this->height());  //设置大小
QList<QTreeWidgetItem *> items;

//创建两个节点
QTreeWidgetItem *fItem1 = new QTreeWidgetItem(treeWidget,QStringList(QString("f1")));
QTreeWidgetItem *fItem2 = new QTreeWidgetItem(treeWidget,QStringList(QString("f2")));

items.append(fItem1);
items.append(fItem2);
//添加顶层节点
treeWidget->insertTopLevelItems(0,items);
//节点始终保持展开
treeWidget->setItemsExpandable(false);
treeWidget->expandAll();

 

2.父节点通过addChild增加子节点

//创建子节点
QTreeWidgetItem *fItem1a = new QTreeWidgetItem(fItem1,QStringList(QString("f1a")));
QTreeWidgetItem *fItem1b = new QTreeWidgetItem(fItem1,QStringList(QString("f1b")));

QTreeWidgetItem *fItem2a = new QTreeWidgetItem(fItem2,QStringList(QString("f2a")));
QTreeWidgetItem *fItem2b = new QTreeWidgetItem(fItem2,QStringList(QString("f2b")));

    //添加字节点
fItem1->addChild(fItem1a);
fItem1->addChild(fItem1b);

fItem2->addChild(fItem2a);
fItem2->addChild(fItem2b);

 

3.建立鼠标点击右键点击信号检测

//检测点击事件
    connect(treeWidget,SIGNAL(itemClicked(QTreeWidgetItem*,int)),this,SLOT(itemClick(QTreeWidgetItem*,int)));
    //检测鼠标右键
treeWidget->setContextMenuPolicy(Qt::CustomContextMenu);
connect(treeWidget,SIGNAL(customContextMenuRequested(const QPoint&)), this,SLOT(popMenu(const QPoint&)));

4.槽函数

void Widget::itemClick(QTreeWidgetItem *item, int column)
{
    QTreeWidgetItem *parent = item->parent();   //获取父节点
    if(NULL==parent) //注意:最顶端项是没有父节点的
        return;
    int col = parent->indexOfChild(item); //item在父项中的节点行号(从0开始)
}

//弹出菜单
void Widget::popMenu(const QPoint &)
{
    QTreeWidgetItem* curItem=treeWidget->currentItem();  //**获取当前被点击的节点
    if(curItem == NULL || curItem->parent() == NULL)
        return;           //右键的位置在空白位置右击或者点击的是顶层item

    //创建一个action
    QAction deleteItem(QString::fromLocal8Bit("&删除"),this);
    connect(&deleteItem, SIGNAL(triggered()), this, SLOT(deleteItem()));
    QPoint pos;
    //创建一个菜单栏
    QMenu menu(treeWidget);
    menu.addAction(&deleteItem);
    menu.exec(QCursor::pos());  //在当前鼠标位置显示
}

//删除item
void Widget::deleteItem()
{
    QTreeWidgetItem* curItem=treeWidget->currentItem();
    curItem->parent()->removeChild(treeWidget->currentItem());
}